首页 文章

仅在表B中没有值的情况下连接表

提问于
浏览
3

我正在尝试连接2个表并过滤不存在的值 .

Table_Items:item_id,title等

Table_History:item_id,history_id,action,date

对于每个光盘,有许多可能的操作(购买,添加,播放,翻录等),每个操作在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 . 帮助将不胜感激!谢谢 .

1 回答

  • 7

    只需将动作过滤器添加到连接中,然后在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
    

    你也可以不做

    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
    

相关问题