我有一个电子商务网站 (MySql/PHP),我需要在其中获取两个连接表的一些结果。这是我所拥有的简化版本:
Table: product[
product_id,
other_irrelevant_stuff,
etc.
]
Table: product_to_category[
product_id,
category_id
]
产品可能有多个类别。我正在使用 product p LEFT JOIN product_to_category p2c ON (p2c.product_id = p.product_id)
。我需要获取分配了两个特定类别的产品的结果。
显然,如果我使用 p2c.category_id = 1 AND p2c.category_id = 2
,我不会得到任何结果,因为不会有任何一个订单项符合这些条件。如果我使用 p2c.category_id = 1 OR p2c.category_id = 2
,我会得到两个类别的所有结果(所有 category_id = 1
和所有 category_id = 2
) 我不想要的。我只想获得同时具有 category_id 1
和 category_id 2
的产品。
我通常很擅长这个,但也许我只是脑放屁。有什么想法吗?
最佳答案
这应该可以使用 group by
和 count
with distinct
:
select p.product_id
from product p
join product_to_category pc on p.product_id = pc.product_id
where pc.category_id in (1,2)
group by p.product_id
having count(distinct pc.category_id) = 2
关于php - 一对多关系的 MySql JOIN 表结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19254039/