与 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
然后,您需要通过添加一个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
正如我所说,我认为将其重新排列为 JOIN 会得到更好的优化,但还没有测试过这个理论。
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