![](/img/trans.png)
[英]Select rows from a table where id in another second table based on second table ids shows results top as well as next results as it is + Mysql
[英]How to omit select results based on IDs from another table in mySQL?
我的目標是我想從我的“users”表中獲取數據庫中的用戶名列表,但是省略其ID也在“projects_users”表中的每個用戶,其中project_id = 1。
換句話說,如果這些是表:
table: users
user_id user_name
1 dave
2 matt
3 james
table: projects_users
user_id project_id
1 2
2 2
3 1
此查詢將返回“dave”和“matt”(因為“james”在users表中,但也與項目#1相關聯,因此省略了它)。
我知道我應該使用某種形式的連接,但我當前的查詢不是這樣做的:
SELECT user_name
FROM users
JOIN projects_users ON (
users.user_id != (projects_users.user_id WHERE projects_users.user_id == 1)
)
這個結果根本不起作用,早期的實驗不斷返回每個名稱的多個副本。 有沒有人知道如何做到這一點,而無需轉向更手動的PHP解決方案?
最后的答案,完美的工作。 也許它沒有像其他一些解決方案那樣優化,但它是唯一一個每次都給我有效結果的解決方案。 出於某種原因,其他解決方案有時會出現意外的名稱,或者根本沒有名稱。 無論如何,這肯定比使用PHP還要長。
SELECT user_id, user_name FROM users WHERE user_id NOT IN (SELECT user_id FROM projects_users WHERE project_id = 1)
謝謝大家的貢獻。 我感謝您的所有幫助和意見。
利用LEFT JOIN
的強大功能。
SELECT u.*
FROM users u
LEFT JOIN project_users pu ON u.user_id = pu.user_id
WHERE pu.project_id IS NULL OR pu.project_id <> 1;
與JOIN
( INNER JOIN
的快捷方式)不同, LEFT JOIN
選擇主表中的所有行及其來自連接表的匹配行,但如果找不到匹配的行,則返回假的一行,並將所有字段設置為NULL
。
當我重新閱讀這個問題時,我覺得我弄錯了。 如果您只想過濾掉與某個項目關聯的用戶,那么這是一個要使用的查詢。
SELECT DISTINCT u.user_id, u.user_name
FROM project_users pu
LEFT JOIN users u ON u.user_id = pu.user_id
WHERE pu.project_id <> 1;
嘗試這個:
SELECT DISTINCT
users.user_id,
user_name
FROM
projects_users
RIGHT JOIN
users
ON
users.user_id = projects_users.user_id
WHERE
projects_users.project_id <> 1
OR
projects_users.project_id IS NULL
請嘗試以下方法:
select u.*
from users u
where exists (select null
from projects_users pu1
where u.user_id = pu1.user_id)
and not exists (select null
from projects_users pu2
where u.user_id = pu2.user_id and pu2.project_id = 1)
或者:
select u.*
from users u
join projects_users pu on u.user_id = pu.user_id
group by u.user_id
having max(case when pu.project_id = 1 then 1 else 0 end) = 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.