目标:
需要有效的频道(channels.active=1
)但有0
个有效项目的结果。
有items
,它们属于channel
。 items
可以有多个渠道。
共有3个表格:
channels
items
items_channels
items_channel
将项目映射到频道。示例行:
id item channel
1 23 47
到目前为止,我只是为了获得活跃的渠道:
SELECT * FROM channels WHERE channels.active = 1
我无法抓住我只加入有0个活动项的频道的部分 - 我是否需要子查询或某个HAVING
某个COUNT
子句?
此外,channels.active
适用于有效频道,items.active
适用于有效频道。
答案 0 :(得分:3)
这是你在找什么?
SELECT * FROM channels c
LEFT OUTER JOIN items_channels ic ON c.channelID = ic.channelID
LEFT OUTER JOIN items i ON i.itemID = ic.itemID AND i.active = 1
WHERE channels.active = 1 AND i.itemID IS NULL
如果使用COUNT(),则需要使用嵌套查询,如:
SELECT * FROM channels c
WHERE channels.active = 1 AND c.channelID IN
(
SELECT ic.channelID FROM items_channels ic
LEFT OUTER JOIN items i ON i.itemID = ic.itemID
WHERE i.active = 1
GROUP BY ic.channelID
HAVING COUNT(ic.itemID) == 0
)
答案 1 :(得分:2)
这应该适合你:
SELECT channels.*
FROM channels
LEFT JOIN items_channels
ON channels.id = items_channels.channel
LEFT JOIN items
ON items_channels.item = items.id AND items.active = 1
WHERE channels.active = 1
GROUP BY channels.id
HAVING COUNT(items.id) = 0
使用sqlfiddle here。