2017-05-14 112 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

相关问题