V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
mart1nN
V2EX  ›  MySQL

sql 语句查询效率的问题

  •  
  •   mart1nN · 2019-05-02 17:07:04 +08:00 · 4103 次点击
    这是一个创建于 1814 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有两个表,score (成绩)和 student (学生),需求是查询学生李四的所有科目的成绩

    select score.c_name, score.grade from score,student where student.name = '李四' and score.stu_id = student.id

    select c_name, grade from score where stu_id= (select id from student where name='李四')

    这两句的查询结果是一样的,请问查询效率哪一条会高一点呢?有关 sql 效率这方面的东西有什么推荐的书 /博客吗?

    6 条回复    2019-05-03 02:07:42 +08:00
    8FollowHeart
        1
    8FollowHeart  
       2019-05-02 17:20:55 +08:00
    1.加上索引 name 和 stu_id 后第一条快
    8FollowHeart
        2
    8FollowHeart  
       2019-05-02 17:21:52 +08:00
    第二种建议少用,student 数据少,性能一般
    winoros
        3
    winoros  
       2019-05-02 18:30:14 +08:00   ❤️ 1
    这两个 SQL 一个是 inner join 一个是 semi join。
    semi join 因为不能让外表的数据膨胀 所以总是只能拿外表查内表。而 inner join 则既可以拿左表查右表 也可以拿右表查左表。这个 case 的实际意义来看,右表(内表)肯定是小的一边。所以 semi join 会不占优势。
    当然优化器实际是可以让两个 SQL 优化成同样的执行计划,但是 MySQL 可能没有做?具体的就要看文档了
    chitanda
        4
    chitanda  
       2019-05-02 18:38:37 +08:00 via Android
    请善用 explain
    JaguarJack
        5
    JaguarJack  
       2019-05-02 20:51:53 +08:00 via iPhone
    explain 之后再来问
    mmdsun
        6
    mmdsun  
       2019-05-03 02:07:42 +08:00 via Android
    想问连表和子查询哪个更快?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4814 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 09:47 · PVG 17:47 · LAX 02:47 · JFK 05:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.