4

I am using PHP and MySQL If I have the following two tables

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 |
--------------

I would like to retrieve the following info:

| 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          |
------------------------------------------------------

I cant think where to begin with this. Cheers

4

2 回答 2

15

尝试以下操作:

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
于 2013-09-02T17:30:34.960 回答
4

这是一个没有子查询的平面解决方案:

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
于 2017-04-06T18:16:18.790 回答