简体   繁体   English

SQL:选择A而不是B的集合

[英]SQL: selecting the set of A not B

I have Two tables: left one is users_projects, right one is projects: 我有两个表:左边一个是users_projects,右边一个是项目: 在此处输入图片说明

I want to select the projects that user 3 is not participating in (only p_ID 5 and 7). 我想选择用户3不参与的项目(仅p_ID 5和7)。

I've tried SELECT * FROM users_projects up INNER JOIN projects p ON p.p_ID=up.p_ID WHERE up.u_ID!=3 我试过SELECT * FROM users_projects up INNER JOIN projects p ON p.p_ID=up.p_ID WHERE up.u_ID!=3

but that also returns me p_ID 1 which both user 2 and 3 are a part of. 但这也返回给我p_ID 1,用户2和3都属于其中。

Thanks for your help! 谢谢你的帮助!

A solution with LEFT JOIN : LEFT JOIN的解决方案:

SELECT 
  * 
FROM 
  projects p LEFT JOIN users_projects up ON (p.p_ID = up.p_ID AND up.u_ID = 3)
WHERE 
  up.u_ID IS NULL

Basically select all Projects and join them with the user_projects of the desired user. 基本上选择所有项目,然后将它们与所需用户的user_projects加入。 Left join makes all rows from the project table appear even if the is no corresponding row in the users_projects table. users_projects使project表中的所有行都出现,即使users_projects表中没有对应的行也是users_projects These rows have all fields from the users_projects set to NULL , so we can just select those. 这些行将users_projects所有字段users_projects设置为NULL ,因此我们可以选择它们。

This is not a JOIN query, but a query with a non-correlated sub-select with a NOT IN() predicate. 这不是JOIN查询,而是具有不相关子选择且带有NOT IN()谓词的查询。

I hope the columns of the projects table are enough ... 我希望projects表的列足够了...

SELECT
  *
FROM 
  (         SELECT 1,'Apple'   -- input data, don't use in 'real' query
  UNION ALL SELECT 5,'Banna'   -- input data, don't use in 'real' query
  UNION ALL SELECT 7,'Carrot'  -- input data, don't use in 'real' query
  UNION ALL SELECT 8,'Durian') -- input data, don't use in 'real' query 
projects(p_id,p_name)
WHERE p_id NOT IN (
  SELECT
    p_id
  FROM 
    (         SELECT 2,1  -- input data, don't use in 'real' query
    UNION ALL SELECT 2,5  -- input data, don't use in 'real' query
    UNION ALL SELECT 2,7  -- input data, don't use in 'real' query
    UNION ALL SELECT 3,1  -- input data, don't use in 'real' query
    UNION ALL SELECT 3,8) -- input data, don't use in 'real' query
  users_projects(u_id,p_id)
  WHERE u_id=3
)
;

p_id|p_name
   7|Carrot
   5|Banna

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM