mysql SQL语句无效

dl5txlt9  于 2022-12-10  发布在  Mysql
关注(0)|答案(2)|浏览(142)

我必须根据以下条件从数据库中提取一个列表:
在下面添加一个列表,显示节目中排名前十的狗。这被定义为平均分数最高的十只狗,前提是它们参加了不止一次比赛。只显示狗的名字、品种和平均分数。
这是我的实现,但它工作不正常,我收到一条错误消息:

Select name, breed, score
from

(Select dogs.name as name, breeds.name as breed, avg(score) as score, count(breeds.id) as count
from entries
join breeds on entries.dog_id = breeds.id
join dogs on breeds.id = dogs.breed_id
group by breed
order by count)x
where count >= 2
group by breed;

1055-SELECT LIST的表达式#1不在GROUP BY子句中,并且包含非聚合列‘u2167487.dogs.name’,该列在功能上不依赖于GROUP BY子句中的列;这与SQL_MODE=ONLY_FULL_GROUP_BY不兼容

我一直在寻找解决方案,但都没有结果

lnvxswe2

lnvxswe21#

您的查询有很多问题。您似乎想要按狗和品种进行聚合,然后根据计数进行过滤,所以我将直接这样做,而不是子查询:

SELECT d.name AS name, b.name AS breed, AVG(score) AS score
FROM entries e
INNER JOIN breeds b ON e.dog_id = b.id
INNER JOIN dogs d ON b.id = d.breed_id
GROUP BY 1, 2
HAVING COUNT(*) >= 2;

确切的错误消息意味着您正在严格的GROUP BY模式下运行MySQL,并且正在选择未出现在GROUP BY子句中的非聚集列。这不是有效的ANSI SQL,因此出现错误消息。

zdwk9cvp

zdwk9cvp2#

您对三个字段执行SELECT操作,但GROUP BY子句中只有一个字段。将所有三个字段添加到GROUP BY子句中,或对未包括的字段应用聚合函数。
使用GROUP BY时,所有列名都必须包含在GROUP BY中,或者对它们应用Aggrigare函数。

Select name, breed, score
from
(Select dogs.name as name, breeds.name as breed, avg(score) as score, count(breeds.id) as count
from entries
join breeds on entries.dog_id = breeds.id
join dogs on breeds.id = dogs.breed_id
group by dogs.name as name, breeds.name
order by count)x
where count >= 2
group by name, breed, score;

在本例中,您可能应该使用HAVING子句

Select * from 
(
Select dogs.name as name, breeds.name as breed, avg(score) as score
from entries
join breeds on entries.dog_id = breeds.id
join dogs on breeds.id = dogs.breed_id
group by dogs.name as name, breeds.name
having count(*) >= 2
) AS x
ORDER BY "count"

相关问题