2014-08-28 13 views
0

我有兩個表;新聞和user_has_readmysql其中鏈接表是空或不等於某些ID

NEWS表

news_id title 
1  happy days 
2  war on the horizion 
3  celebrity does something 

用戶已經閱讀新聞

news_id user_id date 
1  1  jan 1 
1  2  jan 2 
2  1  jan 4 

基本上我想找到所有存在的故事,但還沒有被讀取或尚未由特定用戶讀取 - 這樣我就可以指望通知

因此,像

SELECT 
news_id, 
title 
FROM news 
LEFT OUTER JOIN user_has_read ON 
user_has_read.news_id = news.news_id 
WHERE user_has_read.user_id IS NULL or user_has_read.user_id != 2 

但是這不起作用,有什麼想法嗎?

應該表明USER_ID(2在這種情況下)沒有讀過2層,但它並不

有沒有一種更好的方式去這件事嗎?

+0

結果是什麼?上面的查詢應該從'user_has_read'表中返回'first'和'third'行? – GGio 2014-08-28 21:46:10

+0

是的,它應該但由於某種原因它返回所有3 @GGio – 2014-08-28 21:55:00

回答

1

如果您想要獲取特定用戶尚未閱讀的消息,則必須將該用戶的測試包含在外部聯接的聯接條件中。請把那這不是任何人讀了新聞不太多這個特定用戶閱讀...

SELECT 
    n.news_id, 
    un.user_id 
FROM 
    news n 
LEFT JOIN 
    user_has_read_the_news un 
ON 
    n.news_id = un.news_id AND un.user_id = 2 
WHERE 
    un.user_id IS NULL; 

返回的消息,與id = 2用戶沒有閱讀:

結果與你的示例數據:

news_id | user_id 
----------------- 
     2 | NULL 
     3 | NULL 

對於1的USER_ID結果將是

news_id | user_id 
----------------- 
     3 | NULL 

對於任何其他值的USER_ID爲12結果的用戶將是當然所有新聞:

news_id | user_id 
----------------- 
     1 | NULL 
     2 | NULL 
     3 | NULL 

Demo

+0

他還需要任何人都沒有讀過的所有記錄 – GGio 2014-08-28 21:59:10

+0

任何人都沒有讀過的記錄也不會被這個特定的用戶讀取。包括在內。 – VMai 2014-08-28 21:59:51

+0

這應該是正確的答案 – 2014-08-28 22:06:23

3

您的查詢不工作的原因是:

SELECT story_id, story_name 
FROM stories 
LEFT OUTER JOIN user_has_read.story_id = stories.story_id 
      ^ON is missing 
WHERE user_has_read.user_id IS NULL or != '$user_id' 
            ^syntax error since you are not specifying column 

將其更改爲:

SELECT story_id, story_name 
FROM stories 
LEFT OUTER JOIN ON user_has_read.story_id = stories.story_id 
WHERE user_has_read.user_id IS NULL or user_has_read.user_id != '$user_id' 
上述

假定您正確獲得的$user_id意味着它無論是在雙引號或你的價值正在使用預準備語句。

+0

謝謝,我在問題上非常快速地鍵入查詢,它仍然沒有正確地出來 – 2014-08-28 21:38:29

+0

有一個'ON'丟失 – VMai 2014-08-28 21:38:32

+0

@VMai修正了它。謝謝。 – GGio 2014-08-28 21:39:31

1

VMai的答案是正確的。如果我們在同一時間發佈,並且子查詢是另一種方法,請在此留下。

我會更改爲:

SELECT news_id, title FROM news WHERE news_id NOT IN (
    SELECT news_id FROM user_has_read WHERE user_id=2) 

這就是「從新聞,在新聞ID不在(新聞用戶2已經閱讀)獲得行」。

我認爲另一個選擇可能是:

SELECT news_id, title FROM news 
LEFT OUTER JOIN user_has_read ON (
    news.news_id= user_has_read.news_id AND 
    user_has_read.user_id=2) 
WHERE user_id IS NULL 
相關問題