[英]MySQL 5.7.28 - cannot disable ONLY_FULL_GROUP_BY - non-aggregated columns
[英]With a MySQL GROUP BY, how do I control the default value to choose in non-aggregated columns?
我有下表:
type | description | rank
------------------------|-------
1 | "foo bar baz" | 1
1 | "bar foo baz" | 4
2 | "baz bar foo" | 2
3 | "bar baz foo" | 3
我想要GROUP BY type
,對於所有其他列,返回與MAX(rank)
關聯的值。 顯然MAX(rank)
很容易,但我怎么得到"description ORDER BY rank DESC"
?
您必須選擇max(rank)和self-join來獲取相關描述
select t1.type, t1.max_rank, t2.description from (
select max(rank) max_rank, type
from mytable
group by type
) t1 join mytable t2 on t1.type = t2.type and t1.max_rank = t2.rank
order by t1.max_rank desc
或使用not exists
select * from mytable t1
where not exists (
select 1 from mytable t2
where t2.type = t1.type
and t2.rank > t1.rank
)
order by rank desc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.