0

我正在使用 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

我正在尝试计算一起购买三种产品的次数。这是这个问题的延伸: 寻找客户一起购买的产品

4

2 回答 2

3

您应该遵循与该解决方案相同的方法来获得所有 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;

通过添加更多连接,您应该能够很容易地弄清楚如何将其扩展到更多产品。

于 2013-09-03T16:34:46.573 回答
1

扩展昨天的答案-

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

小提琴

于 2013-09-03T16:42:14.937 回答