每当我使用max函数时,我都会失去与其他值的所有连接,因此稍后打印的行与我再次运行max的列不相关.
所以我的表是:
user col1 col2 col3
1 1 2 3
1 3 4 5
2 2 3 1
3 1 1 3
3 2 4 6
4 5 1 5
所以,如果我跑
select user, col1, col2, max(col3) as col3
from table
group by user
order by user;
我会的
user col1 col2 col3
1 1 2 5
2 2 3 1
3 1 1 6
4 5 1 5
因此col3的最大值是正确的,但它没有得到该值的正确行.
我想要的是获取列的最大值并为每个用户返回该行.如果有多个最大值,它应该返回所有用户,即使它具有相同的用户ID.
解决方法:
其他数据库(例如MS SQL Server)不允许您将aggergated值与非聚合值混合,只是因为您会得到错误的结果.
因此,如果您希望记录中的最大值为非聚合值,请再次对表进行连接:
select x.user, y.col1, y.col2, x.col3
from (
select user, max(col3) as col3
from table
group by user
) x
inner join table y on y.user = x.user and y.col3 = x.col3
order by x.user
标签:sql,mysql
来源: https://codeday.me/bug/20190725/1538242.html