我有一个带有 3 个表的 SQLite 数据库,interests
, events
, categories
。您可以为您的兴趣添加一个类别,我需要编写一个查询来提取所有附加到该类别的事件。
您还可以将事件添加到您的兴趣中,或禁用事件以使其不会显示在类别下方。
例如,对所有“生活大爆炸”剧集感兴趣,但禁用您已经看过的单个剧集。
此查询选择兴趣表中某个类别的所有事件,包括禁用的事件:
SELECT events.id AS event_id, events.title, event_interests.disabled
FROM interests
JOIN events ON events.category_id = interests.id
AND interests.type LIKE "category"
LEFT JOIN interests AS event_interests ON event_interests.id = events.id
AND event_interests.type LIKE "event"
这给出了这些结果:
Event_ID Title Disabled
122749 Bad Education
122815 Bad Education 1
122852 Bad Education
此查询执行完全相同的操作,但仅限于禁用的兴趣
SELECT events.id AS event_id, events.title, event_interests.disabled
FROM interests
JOIN events ON events.category_id = interests.id
AND interests.type LIKE "category"
LEFT JOIN interests AS event_interests ON event_interests.id = events.id
AND event_interests.type LIKE "event"
WHERE event_interests.disabled = 1
仅返回禁用的行
Event_ID Title Disabled
122815 Bad Education 1
但我想获取所有未禁用的事件。但是反转WHERE event_interests.disabled
并没有给我:
SELECT events.id AS event_id, events.title, event_interests.disabled
FROM interests
JOIN events ON events.category_id = interests.id
AND interests.type LIKE "category"
LEFT JOIN interests AS event_interests ON event_interests.id = events.id
AND event_interests.type LIKE "event"
WHERE event_interests.disabled != 1
这给出了一个空白结果集,而不是返回事件122749、122852
我是否对我的 JOIN 做了一些愚蠢的事情?