MYSQL/PHP find the most common item associate with a given item

前端 未结 1 1676
慢半拍i
慢半拍i 2021-01-27 04:41

I have thousands of user generated wish lists of items

the table is something like

collectionId |  itemdId  | user_id
-----------------------------------         


        
相关标签:
1条回答
  • 2021-01-27 05:25

    Start with a query that gets all the collections that contain the item you selected:

    SELECT collectionId
    FROM wishLists
    WHERE itemId = 876
    

    From this, you want to get all the other itemIds in those collections.

    SELECT itemId
    FROM wishLists
    WHERE collectionId IN (above query)
    AND itemId != 876
    

    This can be rewritten as a join:

    SELECT a.itemId
    FROM wishLists AS a
    JOIN wishLists AS b ON a.collectionId = b.collectionId
    WHERE a.itemId != 876 AND b.itemId = 876
    

    Now you can count the repetitions of this to find the most common ones:

    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
    

    Add a LIMIT n clause at the end to show the top n items.

    0 讨论(0)
提交回复
热议问题