MySQL 将 group 函数与 max() 一起使用无效
MySQL Invalid use of group function with max()
我正在尝试 select 一个布尔值,其中 order.lastUpdated 早于 30 分钟前,但我收到错误:
SQL state [HY000]; error code [1111]; Invalid use of group function;
nested exception is java.sql.SQLException: Invalid use of group
function
这里是查询:
select
c.externalReference channelReference,
c.id channelId,
max(o.lastUpdated) lastUpdated,
sum(if(max(o.lastUpdated) < date_sub(now(), interval 30 minute), 0, 1)) beforeThreshold
from channel c
join order_item o on c.id = o.channelId
where date(o.lastUpdated) = date(now())
and o.lastUpdated > date_sub(now(), interval 1 hour)
group by c.externalReference;
如果 o.lastUpdated
早于 30 分钟前我必须使用 max()
,我如何 return 布尔值?
您不能嵌套聚合函数,例如 SUM()
和 MAX()
。您需要在子查询中执行内部查询。
SELECT c.externalReference AS channelReference,
c.id AS ChannelId
o.lastUpdated,
SUM(IF(o.lastUpdated < DATE_SUB(NOW(), INTERVAL 30 MINUTE), 0, 1) AS beforeThreshold
FROM channel AS c
JOIN (SELECT channelId, MAX(lastUpdated) AS lastUpdated
FROM order_item
WHERE DATE(lastUpdated) = TODAY()
AND lastUpdated > DATE_SUB(NOW(), INTERVAL 1 HOUR)
GROUP BY channelId) AS o
ON c.id = o.channelId
GROUP BY c.externalReference
我正在尝试 select 一个布尔值,其中 order.lastUpdated 早于 30 分钟前,但我收到错误:
SQL state [HY000]; error code [1111]; Invalid use of group function; nested exception is java.sql.SQLException: Invalid use of group function
这里是查询:
select
c.externalReference channelReference,
c.id channelId,
max(o.lastUpdated) lastUpdated,
sum(if(max(o.lastUpdated) < date_sub(now(), interval 30 minute), 0, 1)) beforeThreshold
from channel c
join order_item o on c.id = o.channelId
where date(o.lastUpdated) = date(now())
and o.lastUpdated > date_sub(now(), interval 1 hour)
group by c.externalReference;
如果 o.lastUpdated
早于 30 分钟前我必须使用 max()
,我如何 return 布尔值?
您不能嵌套聚合函数,例如 SUM()
和 MAX()
。您需要在子查询中执行内部查询。
SELECT c.externalReference AS channelReference,
c.id AS ChannelId
o.lastUpdated,
SUM(IF(o.lastUpdated < DATE_SUB(NOW(), INTERVAL 30 MINUTE), 0, 1) AS beforeThreshold
FROM channel AS c
JOIN (SELECT channelId, MAX(lastUpdated) AS lastUpdated
FROM order_item
WHERE DATE(lastUpdated) = TODAY()
AND lastUpdated > DATE_SUB(NOW(), INTERVAL 1 HOUR)
GROUP BY channelId) AS o
ON c.id = o.channelId
GROUP BY c.externalReference