2011-09-01 27 views
3

我试图加入2个表格并对值不存在进行过滤。仅当表中的值不在表中时才加入表格

Table_Items:ITEM_ID,标题等

Table_History:ITEM_ID,history_id,行动,日期

每个光盘有许多可能的行动(购买,补充,发挥,撕裂等),每个动作产生由item_id链接的table_history中的新行。我正在查找的查询将返回所有尚未翻录的光盘。我的查询返回的行太多,所有内容都会返回,因为每个项目的历史记录表中至少有一个条目。

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。帮助将不胜感激!谢谢。

回答

7

的动作过滤器只需添加到一起,然后测试空(反连接),在那里

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 
+0

谢谢!如果'history.action.item_id'更改为'history.item_id',则第二种解决方案效果很好。 – James

+0

@James I更新了答案 –

相关问题