2016-03-16 83 views
1

我有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 

回答

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) 
+0

這是左相當於用一個空支票響應 –

3

方法:使用LEFT JOIN與空檢查

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 
+0

感謝加入,我想你的解決方案,它的工作也一樣,它返回與其他的答案相同的結果。我會upvote它謝謝! – NomNomNom

+0

我相信@DhruvJoshi建議的LEFT JOIN方法更好,這是一個簡單的JOIN操作,其中GROUP/HAVING方法可能需要更多開銷。但是,您應該檢查預計的查詢計劃以驗證它。 – Antonio