2017-05-14 110 views
0

我有2個表,我需要SQL查詢女巫將選擇IDB,從基本表名稱排除我們沒有鏈接例如黃色。在其他表中列表中不包含特定值的行

basic_table: 
idb... name ... value 
1  color red 
2  style modern  

second_table 
id ... idb ... second 
1  1  green 
2  1  yellow 
3  2  red 
4  2  blue 

的結果應該是:

idb... name 
2  style 

這個查詢將包括IDP 1,因爲我們有綠色有,但應排除在外。

SELECT 
    `basic_table`.`idp`, `basic_table`.`name` 
FROM 
`basic_table` 
    LEFT JOIN `second_table` 
     ON (`basic_table`.`idp` = `second_table`.`idp`) 
WHERE (`second_table`.`second` NOT LIKE '%yellow%') 

任何想法?

回答

2

你可以很容易地做到這一點使用not exists

select idb, 
    name 
from basic_table b 
where not exists (
     select 1 
     from second_table s 
     where b.idb = s.idb 
      and s.second = 'yellow' 
     ); 

使用左連接:

select distinct b.idb, 
    b.name 
from basic_table b 
left join second_table s on b.idb = s.idb 
    and s.second = 'yellow' 
where s.idb is null; 
+0

感謝。第一個查詢起作用,但第二個查詢不起作用(它仍然顯示第一行)。 – Ivan

相關問題