在查询中添加WHERE子句

时间:2018-08-09 09:18:52

标签: sql where

我有以下查询:

select count(case when test_nameb is null then 1 end) 
from ( select a.test_name as test_namea, b.test_name as test_nameb 
       from list_52 a 
       left join motorcontroltests b 
       on a.test_name=b.test_name) x 

通过该查询,我可以在 test_name 列上计算两个表之间的不匹配。 但是我想在motorcontroltests表的此查询中添加 WHERE 子句。而且我不知道该条款放在何处。我尝试过,但总是会出错。

多谢。

4 个答案:

答案 0 :(得分:1)

我不知道如何处理where子句,但可以避免使用subquery

select count(*)
from list_52 a
where not exists (select 1 
                  from motorcontroltests b 
                  where a.test_name = b.test_name and b.version = '2.0'
                 );

您可以直接通过JOIN来表达它:

select sum(case when b.test_name is null then 1 else 0 end) 
from list_52 a left join 
     motorcontroltests b 
     on a.test_name = b.test_name and  b.version = '2.0';

答案 1 :(得分:0)

在连接之后使用where子句,以后再使用on

select count(case when test_nameb is null then 1 end) 
from ( select a.test_name as test_namea, b.test_name as test_nameb 
       from list_52 a 
       left join motorcontroltests b 
       on a.test_name=b.test_name    
      where b.test_name is not null --assuming you want to null check---put your condition
     ) x 

我认为您可以通过使用join来实现

select sum(case when b.test_name is null then 1 else 0 end) 
from list_52 a left join 
     motorcontroltests b 
     on a.test_name=b.test_name

答案 2 :(得分:0)

尝试将b.versionJOIN放在一起:

SELECT SUM(CASE WHEN b.test_name IS NULL THEN 1 ELSE 0 END) Count
FROM list_52 a left join motorcontroltests b on a.test_name=b.test_name 
and b.version='2.0'

答案 3 :(得分:0)

尽管您可以将查询编写为:

select count(case when test_nameb is null then 1 end)
from (select l.test_name as test_namea, mct.test_name as test_nameb
      from list_52 l left join
           motorcontroltests mct
           on l.test_name = mct.test_name and mct.version = '2.0'
     ) x;

但是,这将更简单地写为:

select count(*)
from list_52 l left join
     motorcontroltests mct
     on l.test_name = mct.test_name and mct.version = '2.0'
where mct.test_name is null;

也许更清楚地是:

select count(*)
from list_52 l
where not exists (select 1
                  from motorcontroltests mct
                  where l.test_name = mct.test_name and mct.version = '2.0'
                 );

请注意,表别名是表名称的缩写,而不是任意字母。这样可以更轻松地理解和修改查询。

相关问题