簡體   English   中英

在 SQL 中,我可以在另一列中獲取與它們沒有關聯的特定值的列中的值嗎?

[英]In SQL, can I get the values in one column that don't have a certain value associated to them in another column?

假設我有一個包含兩列的表:user_guid 和 trait。 相同的 user_guid 可以在第二列中以不同的特征出現在表中多次。 像這樣:

-----------------------
user_guid | trait
-----------------------
a123      | tall
a123      | sings
a123      | blonde
b321      | short
b321      | sings

有沒有辦法在 trait 列中獲取所有沒有值“tall”的 user_guid? 我正在嘗試使用 WHERE NOT EXISTS,但我似乎無法讓它工作。

一個簡單的方法是聚合:

select user_guid
from t
group by user_guid
having sum(trait = 'tall') = 0;

注意:這不會返回完全沒有特征的用戶。 為此,您需要一個單獨的用戶表:

select u.*
from users u
where not exists (select 1
                  from t
                  where t.user_guid = u.user_uid and t.trait = 'tall'
                 );

您可以在NOT EXISTS中使用相關子查詢

SELECT DISTINCT t1.user_guid
FROM yourTable AS t1
WHERE NOT EXISTS
    (SELECT 1 FROM yourTable AS t2
     WHERE t2.user_guid = t1.user_guid AND t2.trait = 'tall')

或者您可以使用自加入

SELECT DISTING t1.user_guid
FROM yourTable AS t1
LEFT JOIN yourTable AS t2 ON t1.user_guid = t2.user_guid AND t2.trait = 'tall'
WHERE t2.user_guid IS NULL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM