简体   繁体   中英

SQL join QUERY multiple tables and SELECT's

I build the following query,

        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

The code works perfectly without this part

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

But, I need the query to select all posts from all forums he subscribe to, including the subforums posts.

'fsub' has no scope here, it doesn't really even exist at this point in your query:

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

You need to use a UNION I believe.

Instead of using sub-queries why don't you just add the subscribe and forums table to the main FROM criteria?

eg,

FROM posts
JOIN users ON(users.id = posts.useraid)
JOIN subscribe ON (posts.forumid = subscribe.forumid)
JOIN forums ON (forums.relatedto = posts.forumid)

Try this:

  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

This is your answer, you need first join the subscribe and forms before search it with subquery.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM