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
lusirui
V2EX  ›  MySQL

请教 left join 的效率问题

  •  
  •   lusirui · Oct 11, 2018 · 5102 views
    This topic created in 2798 days ago, the information mentioned may be changed or developed.

    查询 1

    select a.*,b.* left join b on a.id=b.id where a.go=2 limit 10
    

    查询 2

    select a.*,b.* from (select * from a where a.go=2 limit 10) as a left join b on a.id=b.id
    

    请问,在表 a 数据量非常大的情况,把查询 1 改成查询 2 会提升查询效率么。 也就是先通过子查询查出 a 的数据,再进行联查,会比一条联查快么。

    Supplement 1  ·  Oct 11, 2018

    补上: 查询1 少了 from a

    select a.*,b.* from a left join b on a.id=b.id where a.go=2 limit 10
    
    14 replies    2019-03-25 17:21:44 +08:00
    TommyLemon
        1
    TommyLemon  
       Oct 11, 2018
    查询 1 的 from 是 form a ?
    ```sql
    select a.*,b.* left join b on a.id=b.id where a.go=2 limit 10
    ```
    fffflyfish
        2
    fffflyfish  
       Oct 11, 2018
    当然会快了,从原来的大表 join 变成小表 join,某种程度上避免了数据倾斜
    akira
        3
    akira  
       Oct 11, 2018
    会。 这种问题,你分别对这 2 条 sql 做下 explain,就能看到区别的了
    lusirui
        4
    lusirui  
    OP
       Oct 11, 2018
    @TommyLemon 哦,对,是 from a,我忘写了
    TommyLemon
        5
    TommyLemon  
       Oct 11, 2018
    EXPLIAN 给出的执行过程是不一样的,第二个多了一个临时表的 SELECT,所以快不快和数据量有关
    carlclone
        6
    carlclone  
       Oct 11, 2018 via Android
    正确做法不是给 on 右边的字段加索引么
    TommyLemon
        7
    TommyLemon  
       Oct 11, 2018
    @TommyLemon 最好还是自己在生产环境排除干扰后多次反复试验,哪个快用哪个
    TommyLemon
        8
    TommyLemon  
       Oct 11, 2018   ❤️ 1
    @TommyLemon
    既然 a 表很大,可以拆分 SQL,在应用层 JOIN:
    ```sql
    select * from a where a.go=2 limit 10
    ```
    取出 a 的所有 id: [1,2,3...],然后:
    ```sql
    select * from b where id IN(1,2,3...)
    ```
    lusirui
        9
    lusirui  
    OP
       Oct 11, 2018
    @carlclone on 右边索引时有的,查询 1 和查询 2 都一样
    lusirui
        10
    lusirui  
    OP
       Oct 11, 2018
    @TommyLemon 好的,谢谢,我也是看了 explain,没看出什么区别,而且查询 2 比查询 1 确实多一条 derived 的查询
    dbolo123
        11
    dbolo123  
       Oct 11, 2018 via Android
    能贴下 explain 吗
    mmdsun
        12
    mmdsun  
       Oct 16, 2018 via Android
    @TommyLemon 这样拼 SQL。会有长度限制吧
    TommyLemon
        13
    TommyLemon  
       Oct 17, 2018
    @mmdsun id 在 1w 个以上可能会导致缓冲区溢出,这时就需要分批处理了
    isrfr
        14
    isrfr  
       Mar 25, 2019 via Android
    limit 放里面?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5437 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 08:40 · PVG 16:40 · LAX 01:40 · JFK 04:40
    ♥ Do have faith in what you're doing.