Start med en forespørgsel, der henter alle de samlinger, der indeholder det element, du valgte:
SELECT collectionId
FROM wishLists
WHERE itemId = 876
Herfra ønsker du at få alle de andre itemId'er i disse samlinger.
SELECT itemId
FROM wishLists
WHERE collectionId IN (above query)
AND itemId != 876
Dette kan omskrives som en joinforbindelse:
SELECT a.itemId
FROM wishLists AS a
JOIN wishLists AS b ON a.collectionId = b.collectionId
WHERE a.itemId != 876 AND b.itemId = 876
Nu kan du tælle gentagelserne af dette for at finde de mest almindelige:
SELECT a.itemId
FROM wishLists AS a
JOIN wishLists AS b ON a.collectionId = b.collectionId
WHERE a.itemId != 876 AND b.itemId = 876
GROUP BY a.itemId
ORDER BY COUNT(*) DESC
Tilføj en LIMIT n
klausul i slutningen for at vise de øverste n elementer.