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

编写 SQL 你都有哪些优化原则和建议

  •  
  •   lyning · Mar 17, 2016 · 3586 views
    This topic created in 3851 days ago, the information mentioned may be changed or developed.
    我想到了两条;
    1 : 多表查询查询,数据量越小的表放最右边(亲测,是这么回事,但是不清楚原理,希望有朋友可以跟我讲一下在查询的过程中都发生了什么)。
    2 :多表查询,特别对于数据量大的表,能先过滤先过滤在联查,这样可以减少笛卡尔积,提速不少。
    最后抛一个疑问
    现有 A B 两个表, A 表中有 150w 数据 , B 有 100 条
    1: select a.id, b.id, count(b.id) from A a left join B b on a.bid=b.id and b.is_exists=1 group by b.id;
    2: select a.id, b.id, count(b.id) from A a left join B b on a.bid=b.id where b.is_exists=1 group by b.id;
    这两条 sql 的运行效率差好大, 1 的效率比 2 的效率慢了 3 倍(用 mysql 测试),网上查了一下资料说 left join 会产生一张临时表, on 条件是在临时表建立之间过滤, where 条件是在临时表建立之后再过滤,但是效率居然差那么多,这到底是怎么回事,有朋友可以帮我解决这个疑问吗?
    2 replies  •  2016-03-18 09:46:48 +08:00
    devinww
        1
    devinww  
       Mar 17, 2016
    lyning
        2
    lyning  
    OP
       Mar 18, 2016
    @devinww 不对,我测试了一下,虽然 left join 加上 where 效率很接近 inner join 但是明显 left join 在 on 条件的时候因为没有过滤,导致效率上稍稍比 inner join 差一点点
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   759 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 21:30 · PVG 05:30 · LAX 14:30 · JFK 17:30
    ♥ Do have faith in what you're doing.