将计数查询合并为一个

Join count query into one

我有两个非常简单的计数查询,我想合并为一个。

为了澄清情况,我将添加我得到的表格:

isbn author
1111 GB
2222 DC
3333 RL

作者

code Name
GB George B.
KL Kyle L.
DC Donald C.
RL Roland L.

合著者

name isbn
KL 1111
GB 2222
GB 3333

以及我提出的查询: 查询 1:

SELECT a.name, count(*) 
FROM coauthor c INNER JOIN author a ON c.name = a.code
GROUP BY a.name

给出:

name Count(*)
KL 1
GB 2

查询 2:

SELECT a.name, count(*) 
FROM author a INNER JOIN book b ON a.code = b.author
GROUP BY a.name

给出:

name count(*)
GB 1
DC 1
RL 1

所以我想得到:

name count(*)
George B. 3
Donald C. 1
Roland L. 1
Kyle L. 1

我一直在网上搜索,但我想我不知道从哪里开始。

联合合著者和书籍,然后将这些独特的结果加入作者

SELECT q.code as Name
-- , a.name as Author
, COUNT(*) as Total
FROM
(
    SELECT name AS code, isbn
    FROM coauthor
    UNION
    SELECT author, isbn
    FROM book
) q
JOIN author a
  ON q.code = a.code
GROUP BY q.code, a.name
ORDER BY q.code

请注意,正常 UNION 会过滤掉重复的行。
UNION ALL 保留重复的行。

您可以使用 LEFT 加入 AuthorBookCoauthor 并聚合:

SELECT a.code, a.name, 
       COUNT(DISTINCT b.isbn) + COUNT(DISTINCT c.isbn) count
FROM Author a
LEFT JOIN Book b ON b.author = a.code
LEFT JOIN Coauthor c ON c.name = a.code
GROUP BY a.code, a.name;

参见demo