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

时间:2016-03-16 11:17:49

标签: sql sql-server join

我有2个表:useraddress

我想查询并显示表user中没有关联address'的所有用户。

我的查询如下,但可能由于having子句而无效。它会引发错误。

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 

2 个答案:

答案 0 :(得分:3)

您可以使用NOT EXISTS

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

答案 1 :(得分:3)

方法:使用LEFT JOIN和NULL检查

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

说明:

我们通过LEFT JOIN计算出一组所有用户添加了地址信息,然后使用WHERE子句我们过滤掉了没有地址的用户所需的记录集

为什么您的查询不起作用,因为您使用的having没有group by。修正后的语法是

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