Oracle实际上执行的是正确的行为。当您使用GROUP BY
时,选择列表中的项目必须出现在GROUP BY
或集合函数中。
SELECT order1.user_id,
order1.order_datetime,
SUM(order2.order_total)
FROM order_table order1
JOIN order_table order2 ON order1.user_id = order2.user_id
GROUP BY order1.user_id, order1.order_datetime
MySQL使用一个EXTENSION TO GROUP BY
允许不执行该FULL GROUP BY的行为。在MySQL中使用它并不能保证order1.order_datetime
的值是什么,MySQL只选择一个值,结果可能是意外的。
您需要使用GROUP BY
或在SELECT
列表中的所有项目上进行汇总(与上面类似),或者您必须重新编写查询。您可以使用任何如下:
SELECT order1.user_id,
min(order1.order_datetime) order_datetime,
SUM(order2.order_total)
FROM order_table order1
JOIN order_table order2 ON order1.user_id = order2.user_id
GROUP BY order1.user_id
,一个总量适用于order_datetime
,那么你不通过之日起必须组。
您可以使用sum() over()
:
SELECT order1.user_id,
order1.order_datetime,
SUM(order2.order_total) over(partition by order1.user_id) order_total
FROM order_table order1
JOIN order_table order2 ON order1.user_id = order2.user_id
或者这可以使用子查询重写。
SELECT order1.user_id,
order1.order_datetime,
order2.order_total
FROM order_table order1
JOIN
(
select SUM(order_total) order_total, user_id
from order_table
group by user_id
) order2
ON order1.user_id = order2.user_id
因为MySQL不喜欢小猫。 – Kermit 2013-02-27 18:22:28
因为MySQL认为只需选择任意'order1.order_datetime'即可。在其他严重的数据库平台中,won syntax语法是不合法的。仅仅因为MySQL对语法的松懈并不能使它正确。 – 2013-02-27 18:25:41