MYSQL / PHP查找与给定项目关联的最常见项目

我有成千上万个用户生成的商品愿望清单

桌子有点像

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

    123      |    2345  |    1
    123      |    3465  |    1
    123      |    876   |    1  // <---
    123      |    567   |    1           
    123      |    980   |    1  // <---

    777      |    980   |    2  // <---
    777      |    332   |    2
    777      |    3465  |    2
    777      |    876   |    2  // <---
    777      |    678   |    2
    777      |    567   |    2
    ...           ...       ...
etc..

您会看到项目876和980都包含在两个系列(777和123)中,因此很受欢迎

所以说我访问了项目876的页面
我想向我的用户显示一个非常常见的项目,它与之关联/合并在一起,是项目980(当然这是基于用户的品味)

Think for a moment what Amazon does, if you see a white iphone i want
to suggest you a pink iphone cover because many other users have
suggested/favorited that together with the white iphone

PHP中,我可能会像在伪代码中那样做一些循环

for total number of collection:

select all item from collection 1

  select all item from collection 2
  do array_interesct (c1,c2)
  store the matching items
  repeat...

  select all item from collection 2
  do array_interesct (c1,c3)
  store the matching items
  repeat...

...then elect all item from collection 2 and repeat all the iterations..

但我想知道这是否只能通过MysqL来完成

解决方法:

一个查询开始,该查询获取包含所选项目的所有集合:

SELECT collectionId
FROM wishLists
WHERE itemId = 876

由此,您想要获得那些集合中的所有其他itemIds.

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

可以将其重写为联接:

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

现在,您可以计算重复次数以找到最常见的重复次数

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

在末尾添加LIMIT n子句以显示前n个项目.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...