我有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)
現在就不清楚怎么優化,望賜教!
uj5u.com熱心網友回復:
在關聯條件列加上索引DISTINCT 替換 GROUP BY
SELECT
a.*,
b.title,
c.username
FROM
(select DISTINCT uid,productID from stock_flow ) a
JOIN product b ON a.productID = b.id
left join user c ON a.uid = c.id
order by a.uid ASC
uj5u.com熱心網友回復:
兄弟,這樣不行呀 弄完 情況更糟糕了 stock_flow Extra出現 Using index for group-by,其他沒變
uj5u.com熱心網友回復:
不可能更差,explain 曬全圖轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/175194.html
標籤:MySQL
