1

我构建以下查询,

        SELECT
        posts.id,
        posts.useraid,
        posts.useradn,
        posts.title,
        posts.createdate,
        posts.forumid,
        posts.type,
        posts.totalreplys,
        users.photo AS creatorphoto
    FROM posts
    JOIN users ON(users.id = posts.useraid)
    WHERE posts.forumid IN(
        SELECT subscribe.forumid AS fsub
        FROM subscribe  
        WHERE subscribe.useraid = '$myid'
    ) AND
    posts.forumid IN(
        SELECT forums.id
        FROM forums
        WHERE forums.relatedto=fsub
    )
    AND posts.type='post' 
    ORDER BY posts.timee DESC LIMIT 20

没有这部分代码可以完美运行

AND
    posts.forumid IN(
        SELECT forums.id
        FROM forums
        WHERE forums.relatedto=fsub
    )

但是,我需要查询来选择他订阅的所有论坛中的所有帖子,包括子论坛帖子。

4

4 回答 4

0

'fsub' 在这里没有范围,在您的查询中此时甚至不存在:

posts.forumid IN(
    SELECT forums.id
    FROM forums
    WHERE forums.relatedto=fsub
)

我相信你需要使用一个 UNION 。

于 2013-03-11T23:22:53.003 回答
0

您为什么不直接将订阅和论坛表添加到主要的 FROM 标准中,而不是使用子查询?

例如,

FROM posts
JOIN users ON(users.id = posts.useraid)
JOIN subscribe ON (posts.forumid = subscribe.forumid)
JOIN forums ON (forums.relatedto = posts.forumid)
于 2013-03-11T23:30:47.207 回答
0

尝试这个:

  SELECT
        posts.id,
        posts.useraid,
        posts.useradn,
        posts.title,
        posts.createdate,
        posts.forumid,
        posts.`type`,
        posts.totalreplys,
        users.photo AS creatorphoto
    FROM posts
    JOIN users 
    ON users.id = posts.useraid AND posts.`type`='post'
    JOIN subscribe
    ON subscribe.forumid = posts.forumid AND subscribe.useraid = '$myid'
    JOIN forums
    ON posts.forumid = forums.relatedto 
    ORDER BY posts.timee DESC LIMIT 20
于 2013-03-11T23:35:00.580 回答
0

这是您的答案,您需要先加入订阅和表单,然后再使用子查询进行搜索。

SELECT
    posts.id,
    posts.useraid,
    posts.useradn,
    posts.title,
    posts.createdate,
    posts.forumid,
    posts.type,
    posts.totalreplys,
    users.photo AS creatorphoto
FROM posts
JOIN users ON(users.id = posts.useraid)
WHERE posts.forumid IN(
    SELECT subscribe.forumid AS fsub
    FROM subscribe ,forums
    WHERE subscribe.useraid = '$myid'
    and forums.relatedto = subscribe.forumid
    and forums.id = subscribe.forumid     
) 
AND posts.type='post' 
ORDER BY posts.timee DESC LIMIT 20
于 2013-03-12T05:59:03.987 回答