SQL查询以查找具有复杂条件的空值

时间:2016-09-20 18:46:00

标签: sql sql-server

我有一个与另一个表(table1 - 包含客户联系信息)相关的主表(table2 - 包含客户主要信息),常用值为ID

在主表中,ID值给我1行,另一个表可能会给我更多行,具体取决于客户有多少联系类型,例如:

  • main_phone(此行始终存在)
  • HOME_PHONE
  • work_phone
  • 手机等。

我想要实现的目标:

首先,我想检查移动值,如果行丢失或没有移动值,但行存在,那么我想检查main_phone值。

但是如果有mobile值,那么我不想检查main_phone值。 如果main_phone值也缺失,那么我想要这些记录。

目前我有查询:

Select customer 
From table1 t1 
Join table2 t2 on t1.id = t2.id
Where t2.type in (main_phone, mobile)
  And t2.type_values in ('',null,'-')

但问题是,如果客户有手机号码和缺少电话号码,这些客户记录也会显示在结果中。

3 个答案:

答案 0 :(得分:0)

这可能会让你接近......

SELECT  customer
FROM    table1 t1 
WHERE   NOT EXISTS (
    SELECT  1
    FROM    table2 t2 
    WHERE   t1.id = t2.id
            AND t2.type in (main_phone, mobile)
            and ISNULL(t2.type_value,'') NOT IN ('','-')
)

如果在NOT EXISTS查询中找到一个值,它将被排除

答案 1 :(得分:0)

您必须小心并将null视为特殊值。以下两个查询将返回不同的结果。

Select COUNT(*) from table1 t1 
join table2 t2 on t1.id=t2.id
where t2.type in (main_phone, mobile)
and t2.type_values in ('',null,'-')

Select COUNT(*) from table1 t1 
join table2 t2 on t1.id=t2.id
where t2.type in (main_phone, mobile)
and (t2.type_values IS NULL) OR(t2.type_values in ('','-'))

您应该养成使用空对比测试null的习惯,例如X IS NULL,NOT X IS NULL,ISNULL()或COALESCE()。

答案 2 :(得分:0)

你想要这样的东西吗?

SELECT 
    customer 
FROM 
    table1 t1 JOIN
    (SELECT 
        id 
    FROM 
        table1 t1 JOIN 
        table2 t2 ON 
        t1.id=t2.id
    WHERE 
        t2.TYPE = mobile AND 
        (t2.type_values IS NULL OR
        t2.type_values IN ('','-') ))  missing_mobile ON
    t1.id = missing_mobile.id
WHERE   
        t2.TYPE = main_phone AND 
        (t2.type_values IS NULL OR
        t2.type_values IN ('','-') )
相关问题