2014-02-28 62 views
2

對於非常模糊的問題抱歉,但我的問題是我有三個不同的表。一個包含用戶信息的表格,一個用於用戶帖子,另一個用戶喜歡。我想從包含用戶數據和帖子的表中選擇數據,但只返回用戶不喜歡的帖子,而不是由用戶自己發佈。我試圖使用JOINS的不同組合,但沒有成功。MySQL - 如果在其他表上匹配,則排除一個表中的所有行

例如,我想與id來爲用戶選擇的行數= 1

Table users: 
+----+----------+ 
| id | username | 
+----+----------+ 
| 1 |  A | 
| 2 |  B | 
| 3 |  C | 
+----+----------+ 

Table posts: 
+----+---------+ 
| id | user_id | 
+----+---------+ 
| 1 |  1 | 
| 2 |  1 | 
| 3 |  2 | 
| 4 |  3 | 
| 5 |  2 | 
| 6 |  3 | 
+----+---------+ 

Table likes: 
+----+---------+---------+ 
| id | post_id | user_id | 
+----+---------+---------+ 
| 1 |  3 |  2 | 
| 2 |  3 |  1 | 
| 3 |  4 |  1 | 
| 4 |  1 |  3 | 
+----+---------+---------+ 

Result wantend: 
+---------+----------+ 
| post_id | username | 
+---------+----------+ 
|  5 |  B | 
|  6 |  C | 
+---------+----------+ 

我遇到的問題是,我的查詢也返回post_id: 3因爲user_id: 2有喜歡的職位。

我希望你能理解我的問題。

在此先感謝! /安德烈亞斯

+0

什麼是你查詢你的問題提?請使用此查詢編輯問題。 –

回答

2

下面是一個使用not existslikes查詢的方法:

select p.id as post_id, u.username 
from posts p join 
    users u 
    on p.user_id = u.id 
where not exists (select 1 
        from likes l 
        where l.post_id = p.id and l.user_id = 1 
       ) and 
     u.id <> 1; 
0

我認爲你的數據模型是不完全正確,如果「喜好」後增加了使用的「帖子」表。

然而,要回答你原來的問題,您可以排除「喜歡」的帖子這樣說:

SELECT p.post_id, p.user_id FROM 
    post p LEFT JOIN 
    likes l 
    ON p.post_id = l.post_id WHERE l.post_id IS NULL; 
0

要找到沒有另一個表中的匹配行,使用LEFT JOIN,然後選擇外鍵是NULL的行。

SELECT p.id as post_id, u.username 
FROM posts p 
LEFT JOIN likes l ON l.post_id = p.id AND l.user_id = 1 
JOIN users u 
WHERE u.id != 1 and l.post_id IS NULL 
0
SELECT p.id, u.username 

FROM stackoverflow.posts p 
JOIN stackoverflow.users u ON p.user_id = u.id 

WHERE user_id <> 1 
     AND 
     p.id NOT IN 
     (
      SELECT likes.post_id 

      FROM stackoverflow.likes 

      WHERE user_id = 1 
     ); 
相關問題