2016-07-07 235 views
-1

我有查詢MySQL的左連接查詢優化

SELECT P.*, COUNT(L.to) AS likes, U.name AS ownerName, U.username AS ownerUsername, 
    U.picture AS ownerPicture 
FROM sn_posts P LEFT JOIN sn_users AS U 
    ON U.id = P.ownerID 
LEFT JOIN sn_likes AS L 
    ON L.to = P.id 
WHERE (P.ownerID = 69) 
GROUP BY P.id 
ORDER BY P.id DESC 

它採取 - 0.3337秒的時間,

+0

我想優化我上面查詢.. –

+1

你好,歡迎來到SO--請儘量提供更多信息 - 表格結構,數據量,指標等 - 所以人們實際上有辦法幫助你。 –

+0

您可以將索引添加到聯接列中,除此之外,您的查詢對我來說確實很好。 –

回答

0

爲表sn_posts添加一個索引與ownerID場可以 是更好

+0

已經在ownerID上索引,但結果是顯示行0-10(總計11個,查詢花了0.3854秒) –

+0

試試這個:SELECT P. *,COUNT(L.to)AS贊,U.name AS ownerName,U.username AS ownerUsername, U.picture AS ownerPicture FROM sn_posts P LEFT JOIN爲u sn_users ON U.id = P.ownerID AND P.ownerID = 69 LEFT JOIN sn_likes爲L ON L.to = P.id GROUP BY P.id ORDER BY P.id DESC – Joker

+0

錯誤的結果... –