簡體   English   中英

僅在表B中沒有值的情況下連接表

[英]Join tables only where value not in table B

我正在嘗試連接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。 幫助將不勝感激! 謝謝。

只需將動作過濾器添加到連接中,然后在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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM