【问题标题】:SQLite LEFT JOIN ignored by WHERE clauseSQLite LEFT JOIN 被 WHERE 子句忽略
【发布时间】:2013-10-03 14:05:02
【问题描述】:

我有一个包含 3 个表的 SQLite 数据库,interestseventscategories。您可以为您的兴趣添加一个类别,我需要编写一个查询来提取所有附加到该类别的事件。

您还可以根据自己的兴趣添加活动,或禁用活动以使其不显示在类别下方。

例如对所有“生活大爆炸”剧集感兴趣,但禁用您已经看过的单个剧集。

此查询选择兴趣表中某个类别的所有事件,包括禁用的事件:

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 做了一些愚蠢的事情?

【问题讨论】:

    标签: javascript sql sqlite left-join where


    【解决方案1】:

    我想disabled 列可以是NULL。 要针对 NULL 进行测试,您必须始终明确:WHERE disabled IS NULL

    基本上,几乎所有与NULL 的比较都会得出NULL。 所以如果你问“给我所有禁用不是 1 的行”,数据库无法给你带有NULL 的行,因为据它所知,NULL 可能意味着“没有数据,但可能是 1” .

    更多惊喜信息in the documentation

    【讨论】:

    • 它可以是NULL,1或0。我想得到0或NULL
    • 那你必须明确地说:disabled = 0 OR disabled IS NULL.
    • 是的,我可以! WHERE event_interests.disabled IS NULL OR event_interests.disabled = 0 工作正常。谢谢丹尼斯。为什么会这样,看到1 != NULL
    • 1 != NULL 是假的。 1 = NULL 也是错误的。查看我在答案中提供链接的文档中的文章以了解更多详细信息。
    • 啊,好的,很好的编辑,谢谢丹尼斯。我早该想到的,这种 NULL 的事情也发生在 MySQL 上
    猜你喜欢
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2015-01-31
    • 2011-07-06
    相关资源
    最近更新 更多