與SQL一樣,它有助於將其分解成小部分。比如,你首先需要的是所有在短期列出了當前用戶擁有的項目:
SELECT Item_ID
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
WHERE Owner = 1 -- CURRENT USER
接下來,你需要誰擁有在同一個項目短名單的所有用戶,爲了說明我將建立作爲。 IN
聲明,但INNER JOIN可能表現更好。
SELECT Owner
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
WHERE Item_ID IN
-- RESULTS FROM LAST QUERY START
( SELECT Item_ID
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
WHERE Owner = 1 -- CURRENT USER
)
-- RESULTS FROM LAST QUERY END
AND Owner != 1 -- CURRENT USER
然後,您需要把這個限制於那些具有2個或更多,加入GROUP BY
和HAVING
SELECT Owner
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
WHERE Item_ID IN
-- RESULTS FROM LAST QUERY START
( SELECT Item_ID
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
WHERE Owner = 1 -- CURRENT USER
)
-- RESULTS FROM LAST QUERY END
AND Owner != 1 -- CURRENT USER
GROUP BY Owner
HAVING COUNT(DISTINCT tbl_ShortList_Items.Item_ID) > 1
然後,您需要使用tbl_users
得到化身爲這些業主
SELECT User_ID, Avatar
FROM tbl_Users
WHERE User_ID IN
-- RESULTS FROM LAST QUERY START
( SELECT Owner
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
WHERE Item_ID IN
( SELECT Item_ID
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
WHERE Owner = 1 -- CURRENT USER
)
AND Owner != 1 -- CURRENT USER
GROUP BY Owner
HAVING COUNT(DISTINCT tbl_ShortList_Items.Item_ID) > 1
)
-- RESULTS FROM LAST QUERY END
正如我所說,我認爲重新排列這個JOINs會更好地優化,但沒有測試這個理論。
SELECT User_ID, Avatar
FROM tbl_Users
INNER JOIN
( SELECT Owner
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
INNER JOIN
( SELECT Item_ID
FROM tbl_ShortList_Items
INNER JOIN tbl_ShortLists
ON tbl_ShortLists.ID = tbl_ShortList_Items.ShortList_ID
WHERE Owner = 1 -- CURRENT USER
) CurrentUserItems
ON CurrentUserItems.Item_ID = tbl_ShortList_Items.Item_ID
WHERE Owner != 1
GROUP BY Owner
HAVING COUNT(DISTINCT tbl_ShortList_Items.Item_ID) > 1
) MatchUsers
ON MatchUsers.Owner = tbl_Users.User_ID
我覺得你的問題不夠清楚,你能解釋一下嗎?如果你可以使用sqlfiddle會很好 – jcho360
我已經編輯了這個問題,以包含一個簡短的僞代碼,應該使事情變得更清晰。 – BenM