单个查询中的多个select语句

时间:2017-12-26 05:22:10

标签: mysql adodb

目前,我正在尝试从朋友和/或当前用户所关注的人中选择帖子列表。但是,当我添加following表的第二个语句时,我遇到了一个问题。

SELECT * FROM login, threads WHERE login.id=threads.poster_id AND deleted=0 AND login.id
   IN ((SELECT CASE WHEN second_id=? THEN first_id ELSE second_id END FROM friends WHERE first_id=? OR second_id=?)
   AND (SELECT CASE WHEN follower=? THEN following ELSE follower END FROM following WHERE follower=?))
ORDER BY threads.posted DESC LIMIT 20

1 个答案:

答案 0 :(得分:2)

只需对两个子查询使用两个显式IN条件:

SELECT *
FROM login
INNER JOIN threads
    ON login.id = threads.poster_id
WHERE
    deleted = 0 AND
    (login.id IN (SELECT CASE WHEN second_id=? THEN first_id ELSE second_id END
                  FROM friends WHERE first_id=? OR second_id=?) AND
     login_id IN (SELECT CASE WHEN follower=? THEN following ELSE follower END
                  FROM following WHERE follower=?))
ORDER BY
    threads.posted
DESC LIMIT 20;

这可能会修复语法错误,甚至可以提供您期望的输出,但我也觉得我们可以更清楚地清理查询。样本数据将在很长一段时间内实现。