php - LEFT JOIN 选择条件

标签 php mysql select left-join

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 中, 不在 ONLEFT 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/

相关文章:

python - 是否可以将 MySQL Server 与独立的客户端软件一起安装?

php - mysql查询从数据库获取数据并使用php以堆积条形图的形式显示

select - IE9 打印时多选溢出

sql - ORACLE SQL中通过select语句添加带有空度量的行

javascript - 在焦点上选择文本框,在模糊时取消选择

PHPDocumentor 2 和 PHP 7 在 Doctrine 中有 opcache 问题

php - 如何防止 PHP 中的 SQL 注入(inject)?

php - 如何将大型 mysql 数据库表导出到 Excel

php - 如何使用 PHP 和 Github API 在 Github 存储库中创建和更新文件?

php - EC2 上的内存缓存