兄弟们,MySQL三表关联查询优化,求救

我有3张表,分别是物流进出的表(stock_flow)、用户表(user)、商品表(product)。
现在需要关联查询 获取每个用户进出库了什么商品。

stock_flow表结构
id 主键
uid 用户ID
productID 商品ID

user表结构
id 主键
username 姓名

product表结构
id 主键
title 产品名

我自己写的SQL语句

SELECT
    a.*,
    b.title,
    c.username
FROM
    (select * from stock_flow GROUP BY uid,productID) a
     JOIN product b ON a.productID = b.id
     left join user c ON a.uid = c.id
     order by a.uid ASC

这样基本结果就是我要的
然后explain了一下
product表 Extra是 Using temporary; Using filesort
user表 Extra是 Using where; Using join buffer (Block Nested Loop)

现在就不清楚怎么优化,望赐教!

阅读 4.8k
3 个回答

为什么不把title和username写入stock_flow啊,这样就不需要连表了

不改表的话,我感觉直接连表就行了啊

alter table stock_flow add index uid_pid (uid, productID);

SELECT a.*,
    b.title,
    c.username
from stock_flow a,product b,user c where a.productID = b.id and a.uid = c.id order by a.uid ASC;
新手上路,请多包涵

你这个要一次性全部出来吗?不需要加limit吗 如果是统计的话可以放到后台跑 或者可以适当拆分一下sql

表user和product数据量如果不大,可以考虑缓存

推荐问题