Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding products that customers bought together

Tags:

sql

mysql

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

like image 682
Alex McDaid Avatar asked Nov 30 '22 20:11

Alex McDaid


1 Answers

Try the following:

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
like image 91
Miquel Avatar answered Dec 03 '22 08:12

Miquel