I am using PHP and MySQL If I have the following two tables
orders ---- |id| |--| |1 | |2 | |3 | |4 | ---- items ---- |order_id|sku| |------------| | 1
Here is a flat solution without the subquery:
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