我有 3 個表用戶、組和專案。一個用戶只能加入一個組,但可以加入多個專案。所以我有一個成員表,用于用戶和專案之間的多對多關系。它有 2 個外鍵指向 user_id 和 project_id。表用戶的 group_id 指向 group.id 表專案的 group_id 指向 group.id
我只想檢索組中但不參與專案的用戶串列。到目前為止,我只是嘗試在用戶和成員表之間進行左連接,如下查詢:
SELECT "users".* FROM "users" LEFT JOIN members ON users.id = members.user_id
WHERE ( users.group_id = 1 AND
(members.project_id != 2 OR members.project_id is NULL)AND users.is_disabled is FALSE)
ORDER BY id ASC
例如,組 1 中的用戶但加入專案 1 和專案 2。我想過濾組 1 中的用戶串列但不加入專案。然后這個查詢仍然在示例中回傳這個用戶,因為他的 project_id 之一是 1。這種情況的任何解決方案?非常感謝!
uj5u.com熱心網友回復:
一個簡單的WHERE謂詞可以檢查用戶是否屬于一個組。現在,要檢查用戶沒有參與您可以使用的專案NOT EXISTS。
查詢可能如下所示:
select *
from users u
where group_id = 123 -- check the user belongs to group 123
and not exists (
select 1 from members m where m.user_id = u.user_id
and m.project_id = 456 -- check not in project 456
)
uj5u.com熱心網友回復:
我找到了一個答案,我只是得到一個用戶串列,其中包含 project_id = 1 和 group id = 1。然后選擇 group_id = 1 的串列用戶,加上用戶不在第一個串列的串列中的位置。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/383287.html
標籤:PostgreSQL的
