我正在使用PHP和MySQL 如果我有以下两个表
orders
----
|id|
|--|
|1 |
|2 |
|3 |
|4 |
----
items
----
|order_id|sku|
|------------|
| 1 | A |
| 1 | B |
| 1 | C |
| 2 | B |
| 2 | A |
| 3 | A |
| 4 | B |
| 4 | C |
--------------
我想检索以下信息:
| original_SKU | bought_with | times_bought_together |
|--------------|-------------|-----------------------|
| A | B | 2 |
| A | C | 1 |
| B | A | 2 |
| B | C | 2 |
| C | A | 1 |
| C | B | 2 |
------------------------------------------------------
我不知道从哪里开始。 干杯
答案 0 :(得分:10)
尝试以下方法:
SELECT c.original_SKU, c.bought_with, count(*) as times_bought_together
FROM (
SELECT a.sku as original_SKU, b.sku as bought_with
FROM items a
INNER join items b
ON a.order_id = b.order_id AND a.sku != b.sku) c
GROUP BY c.original_SKU, c.bought_with
答案 1 :(得分:3)
这是一个没有子查询的平面解决方案:
SELECT a.sku AS original_SKU, b.sku AS bought_with, count(*) as times_bought_together
FROM items AS a
INNER JOIN items AS b ON a.order_id = b.order_id
AND a.sku != b.sku
GROUP BY a.sku