Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何从左表中没有数据的表中检索数据?_Sql_Sql Server_Join - Fatal编程技术网

Sql 如何从左表中没有数据的表中检索数据?

Sql 如何从左表中没有数据的表中检索数据?,sql,sql-server,join,Sql,Sql Server,Join,我有两个表:user和address 我想查询并显示表user中没有关联地址的所有用户 下面是我的查询,但可能是由于具有子句而无法工作。它会抛出一个错误 select * from user_application join user_address on user_address.user_id = user_application.user_id where address_type = 0 having count(user_address.user_id) = 0 您可以使用不存在:

我有两个表:
user
address

我想查询并显示表
user
中没有关联
地址的所有用户

下面是我的查询,但可能是由于
具有
子句而无法工作。它会抛出一个错误

select * from user_application
join user_address on user_address.user_id = user_application.user_id
where address_type = 0
having count(user_address.user_id) = 0 

您可以使用
不存在

select * 
from user_application as u1
where not exists (select 1
                  from user_address as u2
                  where u2.user_id = u1.user_id)

您可以使用
不存在

select * 
from user_application as u1
where not exists (select 1
                  from user_address as u2
                  where u2.user_id = u1.user_id)

方法:使用带空检查的左连接

select * from user_application
left join user_address on user_address.user_id = user_application.user_id
and  address_type = 0 where user_address.userid is NULL
说明:

我们计算出一组由于左连接而添加了地址信息的所有用户,然后使用WHERE子句筛选出所需的一组没有地址的用户记录

关于为什么查询不起作用,因为您使用了
having
而没有
groupby
。正确的语法是

select 
  user_application.user_id -- you can only select the column used in group by 
 from user_application
 join user_address on user_address.user_id = user_application.user_id
where address_type = 0
group by user_application.user_id
having sum(case when user_address.user_id is null then 0 else 1 end) = 0 

方法:使用带空检查的左连接

select * from user_application
left join user_address on user_address.user_id = user_application.user_id
and  address_type = 0 where user_address.userid is NULL
说明:

我们计算出一组由于左连接而添加了地址信息的所有用户,然后使用WHERE子句筛选出所需的一组没有地址的用户记录

关于为什么查询不起作用,因为您使用了
having
而没有
groupby
。正确的语法是

select 
  user_application.user_id -- you can only select the column used in group by 
 from user_application
 join user_address on user_address.user_id = user_application.user_id
where address_type = 0
group by user_application.user_id
having sum(case when user_address.user_id is null then 0 else 1 end) = 0 

这相当于带有空检查的左连接这相当于带有空检查的左连接感谢您的响应,我尝试了您的解决方案,它也有效,它返回与其他人的答案相同的结果。我会投票的谢谢!我相信@DhruvJoshi建议的左连接方法要好得多,这是一个简单的连接操作,其中GROUP/HAVING方法可能需要更多的开销。但是你应该检查估计的查询计划来验证它。谢谢你的回复,我尝试了你的解决方案,它也很有效,它返回的结果与其他人的答案相同。我会投票的谢谢!我相信@DhruvJoshi建议的左连接方法要好得多,这是一个简单的连接操作,其中GROUP/HAVING方法可能需要更多的开销。但是您应该检查估计的查询计划以验证它。