2016-08-08 70 views
-2

我想从SQL结果:SQL - 如果选择不选择B,则选择b,否则没有

我有2种选择:

Select columnA from table1; 

Select columnA, columnB, columnC from table2; 

我想要回第二选择如果来自选择1的所有结果都不会像选择2.

实施例的%columnA%:从选择1 结果;

Hot Dog 
Hamburger 
Fries 

结果来自Select 2;

Shake | Chocolate | 100 cal 
Fries | Curly | 200 cal 

希望能得到结果(后如果):

Shake | Chocolate | 100 cal 
+3

我想你可以问一个更好的问题。 – Strawberry

回答

1

你想有选择2,其结果过滤,所以使用where子句:

Select columnA, columnB, columnC 
from table2 
where columnA not in (select columnA from table1); 

万一columnA表1中可以为空,你就必须添加where columnA is not null到内部查询,或者使用相关not exists查询,而不是not in

这里是not exists相同:

Select columnA, columnB, columnC 
from table2 
where not exists (select * from table1 where table1.columnA = table2.columnA); 

如果你真的想用通配符匹配,更改后的查询:

Select columnA, columnB, columnC 
from table2 t2 
where not exists 
(
    select * 
    from table1 t1 
    where t1.columnA like '%' + t2.columnA + '%' 
); 
+0

虽然不是真的会给你通配符 - 除非OP并不真正意味着要包括那些? –

+1

@David T. Macknet:你说得对。我错过了。在这种情况下,人们必须使用'not exists'。我会添加这个。 –

+0

我更喜欢使用N个时,因为如果有一个NULL它不会给你预期的结果的方法可行的存在。所以我喜欢你添加了这个答案,但是你的声明仍然没有使用类似的。 WHERE table2.ColumnA LIKE + '%' table1.ColumnA + '%' – Matt

1
SELECT t2.* 
FROM 
    table2 t2 
    LEFT JOIN table1 t1 
    ON t2.ColumnA NOT LIKE '%' + t1.ColumnA + '%' 
WHERE 
    t1.ColumnA IS NULL 
相关问题