【问题标题】:Join tables only where value not in table B仅在值不在表 B 中的情况下加入表
【发布时间】:2011-09-01 20:10:05
【问题描述】:

我正在尝试加入 2 个表并过滤不存在​​的值。

Table_Items:item_id、标题等

Table_History:item_id、history_id、动作、日期

对于每张光盘,有许多可能的操作(购买、添加、播放、翻录等),每个操作都会在 table_history 中创建一个由 item_id 链接的新行。我正在寻找的查询将返回所有尚未翻录的光盘。我的查询返回了太多行,因为每个项目在历史记录表中至少有一个条目,所以所有内容都返回了。

SELECT items.item_id, items.title AS Title, items.`author/creator`, history.action 
FROM items
LEFT JOIN history ON items.item_id = history.item_id
WHERE history.action NOT LIKE 'Ripped%' GROUP BY items.item_id ORDER BY title

我正在使用 mySQL。帮助将不胜感激!谢谢。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    只需将操作过滤器添加到联接中,然后在 where 中测试 null(反联接)

    SELECT items.item_id, 
           items.title AS title, 
           items.`author/creator`, 
           history.ACTION 
    FROM   items 
           LEFT JOIN history 
             ON items.item_id = history.item_id 
                AND history.ACTION LIKE 'Ripped%' 
    WHERE  history.item_id IS NULL 
    GROUP  BY items.item_id 
    ORDER  BY title 
    

    你也可以做一个 not in

    SELECT items.item_id, 
       items.title AS title, 
       items.`author/creator`, 
       history.ACTION 
    FROM   items 
           LEFT JOIN history 
             ON items.item_id = history.item_id 
    WHERE  history.item_id NOT IN (SELECT history.item_id 
                                          FROM   history 
                                          WHERE  history.ACTION LIKE 'Ripped%') 
    GROUP  BY items.item_id 
    ORDER  BY title 
    

    【讨论】:

    • 谢谢!如果将“history.action.item_id”更改为“history.item_id”,则第二种解决方案效果很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2018-04-11
    • 1970-01-01
    • 2016-09-02
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多