2014-10-08 80 views
1

我想選擇所有未被用戶標記爲已讀的帖子。選擇不在查詢中的數據

tbl_post

post_id post_message 
1   hello world 
2   good night 
3   good morning 
4   incredible 
5   cool 

tbl_mark_as_read

user_id  post_id 
3    1 
3    4 

我要選擇不會在此查詢

SELECT p.post_id,p.post_message FROM tbl_post AS p 
LEFT JOIN tbl_mark_as_read AS r 
ON r.post_id = p.post_id 
AND r.user_id = 3 

我想選擇的所有數據輸出到像

post_id  post_message 
2    good night 
3    good morning 
5    cool 

回答

3

您可以使用not in操作:

SELECT * 
FROM tbl_post 
WHERE post_in NOT IN (SELECT post_id FROM tbl_mark_as_read); 

如果你想給該用戶3已經閱讀僅僅排除的職位,你可以添加一個where子句內查詢:

SELECT * 
FROM tbl_post 
WHERE post_in NOT IN (SELECT post_id 
         FROM tbl_mark_as_read 
         WHERE user_id = 3); 
+0

這就是我正在尋找的查詢,謝謝你兄弟。 – 2014-10-08 13:28:04

2

試試這個:

SELECT p.post_id,p.post_message FROM tbl_post AS p 
LEFT JOIN tbl_mark_as_read AS r 
ON r.post_id = p.post_id 
AND r.user_id = 3 
where r is null