计数3个表的请求

时间:2016-09-09 19:31:56

标签: mysql

这是我的问题。我有3个表,如

AUTHORS
    id (INT, PRIMARY KEY)
    name (VARCHAR)

WRITINGS
    id (INT, PRIMARY KEY)
    content (TEXT)
    author_id (INT, FOREIGN KEY)

COMMENTS
    id (INT)
    commentary (TEXT)
    author_id (INT, FOREIGN KEY)

我知道如何根据这些请求计算每个用户有多少作品或多少评论:

SELECT A.id, A.name, COUNT(W.id)
FROM AUTHORS AS A
LEFT JOIN WRITINGS AS W
    ON A.id = W.author_id
GROUP BY A.id;

SELECT A.id, A.name, COUNT(C.id)
FROM AUTHORS AS A
LEFT JOIN COMMENTS AS C.author_id
    ON A.id = C.author_id
GROUP BY A.id;

但是有没有办法在一个独特的请求中获得这两个计数(着作和评论)?

其他挑战:同样的问题,但没有嵌套请求。

提前致谢

1 个答案:

答案 0 :(得分:0)

将其中一个查询放入子查询中,并将其与其他查询一起加入。

SELECT A.id, A.name, IFNULL(COUNT(W.id), 0) AS writing_count, IFNULL(C.comment_count, 0) AS comment_count
FROM AUTHORS AS A
LEFT JOIN WRITINGS AS W
    ON A.id = W.author_id
LEFT JOIN (
    SELECT author_id, COUNT(*) AS comment_count
    FROM COMMENTS
    GROUP BY author_id) AS C
    ON A.id = C.author_id
GROUP BY A.id