通过SQL查询找到复杂条件下的空值
问题描述:
我拥有与另一个表(table2
- 包含客户联系信息)相关的主表(table1
- 包含客户主要信息),常用值为ID
。通过SQL查询找到复杂条件下的空值
在主表中的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,'-')
但问题是,如果客户有手机号码和失踪的电话号码,这些客户记录也是在结果中显示。
答
这可能让你关闭..
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查询将被排除
答
你必须要小心,并把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 ('','-'))
你应该在测试使用空比较,如X空的习惯是NULL,不是X IS NULL,ISNULL()或者COALESCE()。
答
你想要这样的东西吗?
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 ('','-'))
显示正确的数据样本和预期的结果 – scaisEdge
这里是一个很好的开始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –
您是否在寻找没有手机或main_phone号码的客户? – Beth