MySQL Group By多连接

时间:2018-07-01 21:20:05

标签: mysql

这是我的SQL查询:

    `SELECT subject, threadpost.date, threadpost.idThreadPost as id,
    threadcategories.category, users.userName, COUNT(idThreadSubs) AS subs, COUNT(idThreadReplies) as replies
    FROM threadpost
      JOIN threadcategories
        ON idthreadcategories = threadpost.category
      JOIN users
        ON idUsers = UserId
      LEFT JOIN threadsubs
        ON threadpost.idThreadPost = threadsubs.ThreadId
      LEFT JOIN threadreplies
        ON threadpost.idThreadPost = threadreplies.ThreadId
    WHERE idthreadcategories LIKE ?
    GROUP BY idThreadPost
    ORDER BY date desc
    LIMIT 20;`

问题在于添加COUNT(idThreadReplies)。如您所见,我按idThreadPost分组。这是因为我想同时检索线程的订阅计数和回复计数。

但是,结果给我的答复数不正确(与订阅数相同)。

我如何正确制定此查询?

1 个答案:

答案 0 :(得分:0)

弄清楚了。解决方案是在需要分组依据的联接中使用子查询:

    `SELECT subject, threadpost.date, threadpost.idThreadPost as id,
    threadcategories.category, users.userName, tsubs.subs AS subs, trep.replies as replies
    FROM threadpost
      JOIN threadcategories
        ON idthreadcategories = threadpost.category
      JOIN users
        ON idUsers = UserId
      LEFT JOIN (
        SELECT threadsubs.ThreadId as tsubId, COUNT(idThreadSubs) as subs
        FROM threadsubs
        GROUP BY idThreadSubs
      ) as tsubs
        ON tsubs.tsubId = threadpost.idThreadPost
      LEFT JOIN (
        SELECT threadreplies.ThreadId as tId, COUNT(threadreplies.idThreadReplies) as replies
        FROM threadreplies
        GROUP BY threadreplies.ThreadId
      ) AS trep
        ON trep.tId = threadpost.idThreadPost
    WHERE idthreadcategories LIKE ?
    ORDER BY date desc
    LIMIT 20;`