2015-02-06 95 views
1
SELECT * FROM messages as t1 
LEFT JOIN 
(
    SELECT topic_id date_seen FROM seen_log_ex WHERE member_id = :uid 
) as t2 
ON t1.topic_id=t2.topic_id AND t2.date_seen < t1.post_date 

如果表t2沒有包含其topic_id,我想從消息中選擇行。LEFT JOIN選擇條件

我想選擇郵件的行如果表t2包含其topic_id和t2.date_seen < t2.post_date

我不想從消息選擇該行,如果表t2包含其topic_id和t2.date_seen >= t2.post_date

我的查詢給出錯誤的結果。我該如何解決它?

+1

您能添加樣本數據以便更好地理解嗎? – Jens 2015-02-06 21:51:21

+0

這是一個論壇腳本。 'messages'表包含像message_id,topic_id,message_content等列。而'seen_log_ex'表包含列member_id,topic_id和date_seen(用戶上次訪問該主題的日期)。我試圖選擇所有未被用戶訪問過的主題或在郵件post_date之前訪問過的郵件。 – Wellenbrecher 2015-02-06 21:55:29

回答

1

看來你還需要member_id = :uid子查詢中,但邏輯的其餘部分應在WHERE,而不是在LEFT JOINON

它還假定seen_log_ex對於每個topic_id都有零或一行。如果它可以有多於一行topic_id結果將不正確。

SELECT * 
FROM 
    messages as t1 
    LEFT JOIN 
    (
     SELECT topic_id date_seen FROM seen_log_ex WHERE member_id = :uid 
    ) as t2 
    ON t1.topic_id=t2.topic_id 
WHERE 
    t2.date_seen < t1.post_date 
    OR t2.topic_id IS NULL 
+0

這一個也適用。謝謝。 – Wellenbrecher 2015-02-06 22:16:31

+1

此查詢和來自已接受答案的查詢將返回不同的結果。你爲什麼說他們都工作? – 2015-02-06 22:19:50

+0

哎呀,對不起。在執行之前,我編輯了另一個查詢。這個答案讓我找到了解決方案,但它本身是錯誤的。我的錯。你的答案是正確的。再次感謝你。 – Wellenbrecher 2015-02-06 22:24:00

1

怎麼樣;

select * from messages m left join seen_log_ex l 
on m.topic_id = l.topic_id 
where 
(l.topic_id is null OR l.date_seen < l.post_date) 
and l.member_id = :uid 
+0

它的工作。謝謝。 -teşekkürler- – Wellenbrecher 2015-02-06 22:16:04

+2

@Wellenbrecher如果表'seen_log_ex'沒有包含'topic_id',那麼這個查詢將不會從'messages'返回一行,因爲'l.member_id =:uid'在where子句中。在這個問題中,有人表示他想要返回這樣的行。 – 2015-02-06 22:18:52

+0

@VladimirBaranov哎呀,對不起。在執行之前,我編輯了這個查詢。這個答案使我找到了解決方案,但它本身是錯誤的。我的錯。 – Wellenbrecher 2015-02-06 22:23:04