我正在尝试获取数据库中比特定作者拥有更多书籍的所有作者的名字。
模式:(LIVRO表示BOOK)
我有这个查询:
SELECT AUTORIA.CODAUTOR, AU.NOMEAUT, COUNT(AUTORIA.CODLIVRO) FROM AUTORIA
INNER JOIN AUTOR AS AU ON AU.CODIGO = AUTORIA.CODAUTOR
GROUP BY AUTORIA.CODAUTOR;
这就是返回值:
+----------+------------------+-------------------------+
| CODAUTOR | NOMEAUT | COUNT(AUTORIA.CODLIVRO) |
+----------+------------------+-------------------------+
| 1 | MACHADO DE ASSIS | 7 |
| 2 | NAVATHE | 6 |
| 3 | ELMASRI | 7 |
+----------+------------------+-------------------------+
现在,我需要使用具有COUNT(AUTORIA.CODLIVRO)列且其值大于作者NAVATHE的值的行来过滤此结果。
这就是我尝试过的:
SELECT AUTORIA.CODAUTOR, AU.NOMEAUT, COUNT(AUTORIA.CODLIVRO) FROM AUTORIA
INNER JOIN AUTOR AS AU ON AU.CODIGO = AUTORIA.CODAUTOR
GROUP BY AUTORIA.CODAUTOR /* Group books by author code */
/* Get authors with more books than NAVATHE */
HAVING COUNT(AUTORIA.CODLIVRO) > COUNT( /* Count how many books NAVATHE has */
SELECT AUTORIA.CODLIVRO FROM AUTORIA /* Obtain the codes of the books of NAVATHE */
INNER JOIN AUTOR AS AU ON AU.CODIGO = AUTORIA.CODAUTOR AND AU.NOMEAUT = 'NAVATHE'
);
但是此查询给我一个错误。
答案 0 :(得分:3)
好吧,获取ID的一种方法是:
SELECT a.CODAUTOR
FROM AUTORIA a
GROUP BY a.CODAUTOR
HAVING COUNT(*) > (SELECT COUNT(*)
FROM AUTORIA a2 JOIN
AUTOR au
ON au.CODIGO = a2.CODAUTOR
WHERE au.nome = 'NAVATHE'
);
我会让您计算JOIN
(或IN
或EXISTS
子句)以获取作者姓名。
答案 1 :(得分:2)
您可以简单地删除子查询周围的COUNT()
,然后将其移至suubquery本身内:
SELECT AUTORIA.CODAUTOR, AU.NOMEAUT, COUNT(AUTORIA.CODLIVRO) FROM AUTORIA
INNER JOIN AUTOR AS AU ON AU.CODIGO = AUTORIA.CODAUTOR
GROUP BY AUTORIA.CODAUTOR
/* Get authors with more books than NAVATHE */
HAVING COUNT(AUTORIA.CODLIVRO) > (
SELECT COUNT(AUTORIA.CODLIVRO) FROM AUTORIA /* Obtain the codes of the books of NAVATHE */
INNER JOIN AUTOR AS AU ON AU.CODIGO = AUTORIA.CODAUTOR AND AU.NOMEAUT = 'NAVATHE'
);