Mysql函数错误为SUM

时间:2016-11-07 14:21:36

标签: mysql

SELECT first_name, last_name, SUM(amount)
FROM customer
LEFT JOIN payment
ON customer.customer_id=payment.amount
ORDER BY amount DESC
LIMIT 10;

我收到错误:

  

#1140 - 在没有GROUP BY的聚合查询中,SELECT列表的表达式#1包含非聚合列'sakila_tak14.customer.first_name';这与sql_mode = only_full_group_by

不兼容

2 个答案:

答案 0 :(得分:1)

V5.7.5& MySQL版本实现了对聚合函数的更严格使用。选择列表中不允许使用非聚合列。 ORDER BY列表(或HAVING子句)。请参阅:https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

您也无法通过金额列&获得您的预期订单(如果您将设置ONLY_FULL_GROUP_BY设置为false选项) - 正如您已将其总结和&结果列将不再被称为金额 - 您需要使用别名。

您需要按第一个和第一个分组。姓氏:

SELECT first_name, last_name, SUM(amount) summedammount
FROM customer LEFT JOIN payment
ON customer.customer_id=payment.amount
GROUP BY first_name, last_name
ORDER BY summedammount DESC
LIMIT 10;

将系统变量ONLY_FULL_GROUP_BY设置为false,或使用ANY_VALUE函数:

SELECT ANY_VALUE(first_name), ANY_VALUE(last_name), SUM(amount) summedammount
FROM customer
LEFT JOIN payment
ON customer.customer_id=payment.amount
ORDER BY summedammount DESC
LIMIT 10;

答案 1 :(得分:0)

您已将金额作为汇总,因此您需要对所有非汇总字段进行分组。试试这个:

SELECT first_name, last_name, SUM(amount)
FROM customer LEFT JOIN payment
ON customer.customer_id=payment.amount
GROUP BY first_name, last_name
ORDER BY amount DESC LIMIT 10;