我在此查询中要选择或显示图书数量高于平均水平的作者。
到目前为止,我要获取平均图书数量的查询如下:
SELECT AVG(c.quantity) AS 'Average'
FROM(
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al
GROUP BY al.autores_DNI
) AS c
然后我该如何仅选择(显示)书籍数量高于平均水平的作者?
此查询列出了作者及其书数:
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al
GROUP BY al.autores_DNI
我尝试过:
SELECT a.first_name
FROM autores AS a
HAVING (
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al
GROUP BY al.autores_DNI
)
> (
SELECT AVG(c.quantity) AS 'Average'
FROM(
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al
GROUP BY al.autores_DNI
) AS c
)
但这不起作用
答案 0 :(得分:2)
您在HAVING
子句中的第一个子查询不仅返回当前作者的计数,还返回所有其他作者的计数。但是SELECT
用作值只能返回一个值。
相反,您应该加入子查询。
SELECT a.first_name
FROM aotores AS a
JOIN (
SELECT al.autores_DNI AS Author,COUNT(*) AS quantity
FROM autores_has_libros AS al
GROUP BY Author) AS al ON al.Author = a.DNI
JOIN (
SELECT AVG(c.quantity) AS Average
FROM (
SELECT COUNT(*) AS quantity
FROM autores_has_libros AS al
GROUP BY al.autores_DNI) AS c
) AS av ON al.quantity > av.Average
顺便说一句,在MySQL中,您使用反引号而不是单引号来引用标识符。单引号用于创建文字字符串。
答案 1 :(得分:0)
您可以尝试将平均值保存在变量中,然后执行选择:
Set @avg = SELECT AVG(c.quantity) AS 'Average'
FROM(
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al
GROUP BY al.autores_DNI
) AS c
SELECT al.autores_DNI AS 'Author',COUNT(*) AS 'quantity'
FROM autores_has_libros AS al where COUNT(*) >= @avg
我不确定这是否行得通,但是您可以对此有所了解。
答案 2 :(得分:0)
如果要使用一个sql语句获取结果,可以尝试使用以下sql:
SELECT a.first_name FROM autores AS a
RIGHT JOIN
(
SELECT autores_DNI AS Author, COUNT(*) AS quantity
FROM autores_has_libros WHERE quantity > (
SELECT AVG(quantity) AS Average FROM
(
SELECT autores_DNI AS Author, COUNT(*) AS quantity
FROM autores_has_libros
GROUP BY autores_DNI
)
)
GROUP BY autores_DNI
) b ON a.author = b.Author
但是,我建议您可以使用语言代码在比较之前获得平均值,或者使用mysql过程。