我正在使用PHP和MySQL
如果我有以下表格
items
----
|order_id|sku|
|------------|
| 1 | A |
| 1 | B |
| 1 | C |
| 1 | D |
| 1 | E |
| 2 | B |
| 2 | C |
| 2 | D |
| 3 | D |
| 3 | E |
| 3 | F |
| 4 | A |
| 4 | B |
| 4 | C |
| 4 | F |
--------------
我想检索以下信息:
| original_SKU | bought_with_a | bought_with_a | times_bought_together |
|--------------|---------------|---------------|-----------------------|
| A | B | C | 2 |
| B | A | C | 2 |
| B | C | D | 2 |
| C | B | D | 2 |
ETC ETC
我正在计算三种产品一起购买的次数。 这是这个问题的延伸: finding products that customers bought together
答案 0 :(得分:3)
您应该采用与该解决方案相同的方法来获得所有三向组合:
SELECT i1.sku as sku1, i2.sku as sku2, i3.sku as sku3, count(*) as bought_together
FROM items i1 join
items i2
on i1.order_id = i2.order_id and i1.sku <> i2.sku join
items i3
on i1.order_id = i3.order_id and i3.sku not in (i1.sku, i2.sku)
GROUP BY i1.sku, i2.sku, i3.sku;
通过添加更多联接,您应该能够轻松地弄清楚如何将其扩展到更多产品。
答案 1 :(得分:1)
延长昨天的answer -
SELECT d.original_SKU, d.bought_with1, d.bought_with2, count(*) as times_bought_together
FROM (
SELECT a.sku as original_SKU, b.sku as bought_with1, c.sku as bought_with2
FROM items a
INNER join items b
INNER join items c
ON a.order_id = b.order_id AND a.order_id = c.order_id AND b.order_id = c.order_id
AND a.sku != b.sku AND a.sku != c.sku AND b.sku != c.sku) d
GROUP BY d.original_SKU, d.bought_with1, d.d.bought_with2
请参阅fiddle