仅从与类别相关的表中获取活动产品

时间:2012-10-14 12:25:05

标签: php mysql sql

我有两张桌子:

1 Category
- cID
- Name
- Active

2 Products
- pID
- Name
- category_id
- active

这是我想要的: 我想要一个仅包含ACTIVE产品的类别列表。

提前致谢

解: SELECT DISTINCT类别。* FROM类别INNER JOIN产品ON category.id = products.c_id WHERE products.active = 0 ORDER BY category.id DESC

3 个答案:

答案 0 :(得分:3)

假设Products.Active = 1表示活跃状态。

SELECT c.*
FROM Category c
INNER JOIN Products p ON c.CID = p.category_id
GROUP BY c.CID
HAVING COUNT(*) = SUM(IF(p.Active = 1, 1, 0)) 

答案 1 :(得分:1)

SELECT * FROM Products
Join Category on Category.ciD = Products.category_id
WHERE Category.Active = 1 AND Products.Active =1

这假设您的活动列只有1或0.否则根据您存储的值进行调整。

答案 2 :(得分:1)

我建议像这样建筑 恕我直言,它的语法显示了您真正想要看到的内容 - 所有具有活动产品的类别

select C.cID, C.Name, C.Active
from Category as C
where C.cID in (select distinct T.category_id from Products as T where T.Active = 1)