1.第一条sql:
SELECT goods.id, goods.name, goods.picture
FROM user_browse_history H
INNER JOIN goods ON H.article_id = goods.id
AND H.article_type =0
WHERE staff_id !=30186
AND article_id !=1015151
GROUP BY staff_id, article_id
LIMIT 52.第二条sql(根据第一条sql改进的)
select id, name, picture from goods where id in (
    select article_id  from (
        select article_id from user_browse_history
        where staff_id != 30186 and article_type = 0 and article_id != 1015151
        group by staff_id, article_id
        limit 5
    ) T
)Explain:user_browse_history的索引有:id, staff_id, article_type, article_id (全是单一的索引,不是联合)sql2要比sql1快多了,没有看出来是什么原因?1.sql2里用id in 无法使用主键索引?
2.这里明明sql2比sql1扫的rows要多,为什么会比sql1要快?
3.什么情况下用inner join 好?什么情况下用in比较好呢?
4.这个sql还有什么优化方案?还请高手指教一下!谢谢!

解决方案 »

  1.   

    注意一下LIMIT的作用和发生的时间导致了SQL2的耗时少。
      

  2.   


    恩。第一个limit是在join goods表之后,第二个limit是在查goods表之前。
      

  3.   


    这里还有一个问题是:
    inner join 和 in子查询各用于什么情况?
    写sql时经常会遇到inner join,难道每次都要运行一下看看哪个效率高再用哪个吗?
      

  4.   


    是的,这本身就是开发人员的职责,写出合理的SQL语句。创建合适的数据库表结构。
      

  5.   


    哦,这个sql的问题也是在数据量大的时候才遇到的。这样在开发前期不好避免啊。有没有好的办法呢?