MySQL的GROUP BY和ORDER BY错误结果
作者:互联网
我有一个表user_comission_configuration_history,我需要从user_id中选择最后一个Comissions配置.
元组:
我正在尝试许多查询,但是结果是错误的.我的上一个SQL:
SELECT *
FROM(
SELECT * FROM user_comission_configuration_history
ORDER BY on_date DESC
) AS ordered_history
WHERE user_id = 408002
GROUP BY comission_id
上面查询的结果是:
但是,正确的结果是:
id user_id comission_id value type on_date
24 408002 12 0,01 PERCENTUAL 2014-07-23 10:45:42
23 408002 4 0,03 CURRENCY 2014-07-23 10:45:41
21 408002 6 0,015 PERCENTUAL 2014-07-23 10:45:18
我的SQL有什么问题?
解决方法:
这是您的查询:
SELECT *
FROM (SELECT *
FROM user_comission_configuration_history
ORDER BY on_date DESC
) AS ordered_history
WHERE user_id = 408002
GROUP BY comission_id;
查询的一个主要问题是它使用MySQL扩展来对MySQL明确警告的分组依据.扩展是使用select中的其他列,这些列不在by函数或聚合函数中.警告(here)为:
MySQL extends the use of GROUP BY so that the select list can refer to
nonaggregated columns not named in the GROUP BY clause. This means
that the preceding query is legal in MySQL. You can use this feature
to get better performance by avoiding unnecessary column sorting and
grouping. However, this is useful primarily when all values in each
nonaggregated column not named in the GROUP BY are the same for each
group. The server is free to choose any value from each group, so
unless they are the same, the values chosen are indeterminate.
因此,列中返回的值是不确定的.
这是一种获取所需内容的非常有效的方法(使用英文正确拼写的“佣金”):
SELECT *
FROM user_commission_configuration_history cch
WHERE NOT EXISTS (select 1
from user_commission_configuration_history cch2
where cch2.user_id = cch.user_id and
cch2.commission_id = cch.commission_id and
cch2.on_date > cch.on_date
) AND
cch.user_id = 408002;
标签:sql,mysql,database,relational-database 来源: https://codeday.me/bug/20191009/1882293.html