从一个表中查找不存在于另一个表中的记录,并在第三个表中忽略

时间:2015-03-08 20:41:18

标签: mysql

基于使用我在此处找到的SQL查询,我希望得到基于user_id的结果。当我将此添加到查询时,我最终得不到任何结果。

SQL - find records from one table which don't exist in another

我有三个表,一个是我的客户的内容,两个是客户同意和正在使用的内容,第三个是要忽略的内容。

我希望获取的结果是内容未被使用或未被忽略。

available_content table
+----+
| id |
+----+
| 1  |
+----+
| 2  |
+----+
| 3  |
+----+
| 4  |
+----+
| 5  |
+----+

posted_content table
+----+----------+
| id | user_id  |
+----+----------+
| 1  | 123      |
+----+----------+
| 2  | 123      |
+----+----------+
| 3  | 456      |
+----+----------+

ignored_content table
+----+----------+
| id | user_id  |
+----+----------+
| 5  | 123      |
+----+----------+
| 1  | 456      |
+----+----------+
| 2  | 456      |
+----+----------+

SELECT a.id
FROM available_content AS a
LEFT OUTER JOIN posted_content AS b
ON (a.id = b.id) WHERE b.id IS NULL AND b.user_id = '123'

results
+----+
| id |
+----+
| 3  |
+----+
| 4  |
+----+

1 个答案:

答案 0 :(得分:2)

SELECT a.id
FROM available_content a
LEFT OUTER JOIN posted_content b ON (a.id = b.id AND b.user_id = '123') 
LEFT OUTER JOIN ignored_content c ON (a.id = c.id AND c.user_id = '123') 
WHERE b.id IS NULL AND c.id IS NULL