0

我不太擅长加入大量表,无法将其放入 SQLite。我有一个包含这些表的数据库:

Feeds->Channels->RegionsChannels->Regions。

其中 Channels 可以通过 RegionsChannels 与 Regions 建立 0 个或多个连接。

Regions 有一个布尔字段 (0, 1),指示用户是否启用了该区域。

我想从 Feeds 中获取一些字段,例如 Feeds.id 和 Feeds.title 用于所有包含与 Regions 没有连接或与 Regions.selected = 1;

我尝试像这样将所有表连接在一起:

select feeds.feed_id, feeds.title
from feeds
    left outer join channels on feeds.feed_id = channels.feed_id
    left outer join regions_channels on channels.channel_id = regions_channels.channel_id
    left outer join regions on regions_channels.region_id = regions.region_id
        and regions.selected = 1
group by feeds.feed_id
order by feeds.feed_id;

试图只获取选定的区域,但它只是给了我所有的提要。我想也许我应该在区域表上做一个 RIGHT OUTER JOIN,但我使用的是 SQLite,它不支持 RIGHT 或 FULL OUTER JOIN。

更新:

我刚试过这个,我得到了我想要的,我已经切换了几个 region.selected 并且每次都恢复得很好。但我不知道它是否真的有效,或者它看起来是否有效,因为我不明白它是如何工作的:

select feeds.feed_id, feeds.title
from feeds
    left outer join channels on feeds.feed_id = channels.feed_id
    left outer join regions_channels on channels.channel_id = regions_channels.channel_id
    left outer join regions on regions_channels.region_id = regions.region_id
where regions._id is NULL
    or regions.selected = 1
group by feeds.feed_id
order by feeds.feed_id;

这对我来说感觉不对,但它有效,所以我现在正在使用它......

4

2 回答 2

0

By putting selected = 1 into the join condition, you have told the database to return either records that match that condition, or (because of OUTER), to return columns filled with NULL. You must put the condition into the WHERE clause so that it is checked after the join.

Second change: I've dropped the LEFT OUTER fropm the feeds/channels join because you did not say you wanted feeds that do not have channels.

SELECT feeds.feed_id, feeds.title
FROM feeds
JOIN channels ON feeds.feed_id = channels.feed_id
LEFT JOIN regions_channels ON channels.channel_id = regions_channels.channel_id
LEFT JOIN regions on regions_channels.region_id = regions.region_id
WHERE regions.selected = 1
   OR regions.selected IS NULL
GROUP BY feeds.feed_id
ORDER BY feeds.feed_id
于 2013-10-01T14:11:08.137 回答
0

你的最后一个AND是修剪regions桌子。

regions.selected=1必须在WHERE子句中。

如果您选择NOT region.selected IS 0,则将显示所有未禁用的提要。

替换GROUP BYDISTINCT- IMO,它更正确。

LEFTLEFT OUTER中相同。

SELECT DISTINCT feeds.feed_id, feeds.title
FROM feeds
    LEFT JOIN channels ON feeds.feed_id = channels.feed_id
    LEFT JOIN regions_channels ON channels.channel_id = regions_channels.channel_id
    LEFT JOIN regions ON regions_channels.region_id = regions.region_id
WHERE NOT regions.selected IS 0
ORDER BY feeds.feed_id;
于 2013-10-01T14:12:34.987 回答