我有一个这样的表TAB:
box_id | product_id | randominfo
1 | a | ...
1 | b | ...
1 | c | ...
2 | a | ...
2 | b | ...
3 | a | ...
3 | c | ...
我想为每对产品提供相同盒中的次数。 像这样:
product 1 | product 2 | number of times
a | b | 2
a | c | 2
b | c | 1
我想到了类似的东西:
SELECT p1.product_id, p2.product_id, COUNT (*) AS nb
FROM TAB p1
LEFT JOIN TAB p2 ON p1.product_id <> p2.product_id
GROUP BY p1.product_id, p2.product_id
ORDER BY nb DESC
我无法检查是否可行。
答案 0 :(得分:0)
您的查询应该没问题,尽管您可能不希望配对出现两次。因此,请使用<
而不是<>
:
SELECT p1.product_id, p2.product_id, COUNT(*) AS nb
FROM TAB p1 JOIN
TAB p2
ON p1.product_id < p2.product_id
GROUP BY p1.product_id, p2.product_id
ORDER BY nb DESC;
除非您要考虑仅包含一种产品的包装盒,否则LEFT JOIN
是不必要的。