我有三个包含分层数据的表:
categories-> feeds-> Feed有FK category_id且频道有FK feed_id的频道。
渠道有一个布尔值,订阅。我想选择所有类别并创建一个订阅(布尔)列,如果其任何Feed中的任何通道为“1”,则该列为“1”。我正在使用SQLite。
首先我尝试了这个:
SELECT categories.category_id, categories.title,
CASE when (channels.subscribed = 1) THEN 1 ELSE 0 END AS subscribed
FROM categories
JOIN feeds ON categories.category_id = feeds.category_id
JOIN channels ON feeds.feed_id = channels.feed_id;
这给了我数据库中每个通道的所有类别,如果channels.subscribed = 1,则categories.subscribed = 1。但是,我只希望结果集中的每个类别一次,如果有的话,categories.subscribed为1订阅了频道。所以我尝试使用group by:
SELECT categories.category_id, categories.title,
CASE when (channels.subscribed = 1) THEN 1 ELSE 0 END AS subscribed
FROM categories
JOIN feeds ON categories.category_id = feeds.category_id
JOIN channels ON feeds.feed_id = channels.feed_id;
GROUP BY categories.category_id;
这给了我想要的结果集,但订阅的列不正确,可以预见:
id|title|subscribed
38|cat1|0
19|cat2|0
虽然我想要这个:
38|cat1|0
19|cat2|1
因为在cat2中有一个包含订阅频道的Feed。是否有一个我可以使用的功能,或者可能是一个更复杂的CASE语句,我必须使其发挥作用?感谢您的帮助和时间。
答案 0 :(得分:0)
SELECT categories.category_id, categories.title,
(select count(distinct channels.subscribed)
from feeds, channels
where categories.category_id = feeds.category_id
and feeds.feed_id = channels.feed_id
and channels.subscribed = 1)
FROM categories
答案 1 :(得分:0)
好的,所以我根据这篇文章说道:
http://weblogs.sqlteam.com/jeffs/archive/2004/07/11/1744.aspx
我可以使用“聚合布尔OR”函数,它只是订阅列上的一个MAX(),以获得我想要的东西,这就是我想到的,我只是无法将它放入SQL中。那么对我有用的是:
SELECT categories.category_id, categories.title,
MAX(CASE when (channels.subscribed = 1) THEN 1 ELSE 0 END) AS subscribed
FROM categories
JOIN feeds ON categories.category_id = feeds.category_id
JOIN channels ON feeds.feed_id = channels.feed_id;
GROUP BY categories.category_id;
如果有人有更好的答案,请发布。