mysql - 为什么 SQL 条件不匹配 "OR"子句?

标签 mysql sql

<分区>

我不知道还能问哪里。我有这个查询:

SELECT po.* FROM posts po, follows f, user pn
                  WHERE (f.follower_id = #{id}
                    AND f.followed_id = pn.id
                    AND po.user_id = pn.id)
                    OR (po.user_id = #{id})
                  ORDER BY created_at DESC LIMIT 10 OFFSET #{offset}

我从关注者那里得到的帖子是正确的,但不是用户自己的帖子。似乎 OR 的第二部分总是被忽略。

SELECT * FROM posts WHERE user_id = #{id}

虽然工作正常。

编辑

对不起,我在完成文本之前不小心按了回车!!

编辑 2

这现在似乎可行了:

SELECT DISTINCT po.* FROM users pn
                    INNER JOIN follows f ON f.follower_id = #{id}
                    INNER JOIN posts po ON po.user_id = f.followed_id OR po.user_id = #{id}
                  ORDER BY created_at DESC LIMIT 10 OFFSET #{offset}

也许有人能告诉我为什么?

最佳答案

试试这个:

SELECT po.* FROM posts po, follows f, user pn
  WHERE f.follower_id = #{id}
    AND f.followed_id = pn.id
    AND (   po.user_id = pn.id
         OR po.user_id = #{id})
  ORDER BY created_at DESC LIMIT 10 OFFSET #{offset}

在第二种情况下没有考虑隐式连接。这是我避免使用隐式连接,而是使用显式 INNER JOIN 子句的原因之一。

如果这没有得到您正在寻找的结果,您可能需要考虑使用 UNION。你的描述有点含糊,你没有给我们你的模式,所以我不知道这个查询是否有效。

关于mysql - 为什么 SQL 条件不匹配 "OR"子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7154706/

相关文章:

php - PHPGraphlib PHP 图表演示黑屏

mysql - 将约束开始添加到mysql中的列

mysql - 每个派生表必须有自己的别名 mysql

sql - 将多个数据源合并到一个统一的表中

mysql - 在 MySQL 中使用自动递增获取最后创建的 ID

mysql - Rails 如何知道我有待处理的迁移?

mysql - 如何根据不等于删除巨大的mysql行

sql - 在 PostgreSQL 中存储我的字符串的最紧凑和最快的方法

sql - Vanilla Postgres,从准备好的语句中选择

php - 如何获取提交后检查的表格单元格中的数据