LEFT JOIN 选择条件
LEFT JOIN selecting conditions
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
如果 table t2 不包含其 topic_id。
,我想 select 消息中的行
如果 table t2 包含其 topic_id 和 t2.date_seen < t2.post_date
,我想 select 消息中的行
如果 table t2 包含其 topic_id 和 t2.date_seen >= t2.post_date
,我不想 select 消息中的行
我的查询给出了错误的结果。我该如何解决?
怎么样;
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
子查询里面好像还需要member_id = :uid
,但是剩下的逻辑应该在WHERE
,而不是LEFT JOIN
的ON
。
它还假设 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
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
如果 table t2 不包含其 topic_id。
,我想 select 消息中的行如果 table t2 包含其 topic_id 和 t2.date_seen < t2.post_date
如果 table t2 包含其 topic_id 和 t2.date_seen >= t2.post_date
我的查询给出了错误的结果。我该如何解决?
怎么样;
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
子查询里面好像还需要member_id = :uid
,但是剩下的逻辑应该在WHERE
,而不是LEFT JOIN
的ON
。
它还假设 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