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,我想从消息中选择行。
如果表 t2 包含其 topic_id 和 t2.date_seen < t2.post_date
,我想从消息中选择行
如果表 t2 包含其 topic_id 和 t2.date_seen >= t2.post_date
,我不想从消息中选择行
我的查询给出了错误的结果。我该如何解决?
最佳答案
看来你还需要member_id = :uid
在子查询中,但其余逻辑应该在 WHERE
中, 不在 ON
的 LEFT JOIN
.
它还假设 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
关于php - LEFT JOIN 选择条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28375387/