0

目标:

channels.active=1需要活动 ( ) 但具有0活动项目的渠道的结果。

items,他们属于channelitems可以有多个通道。

有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适用于活动项目。

4

2 回答 2

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
    )
于 2013-01-08T21:39:14.587 回答
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 。

于 2013-01-08T21:46:47.550 回答