我的问题是:
SELECT SUM(score) score,
type,
context,
post_id,
e.table_code,
comment_id,
MIN(seen) seen,
MAX(date_time) d_t,
(CASE WHEN FROM_UNIXTIME(MAX(date_time)) >= CURDATE() THEN 'today'
WHEN FROM_UNIXTIME(MAX(date_time)) >= DATE_SUB(CURDATE(), INTERVAL 1 DAY) THEN 'yesterday'
WHEN FROM_UNIXTIME(MAX(date_time)) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN 'in last week'
ELSE 'in last month'
END) as range_day
FROM `events` e
WHERE e.id IN ($ids)
GROUP BY type, post_id, e.table_code, comment_id, range_day
ORDER BY seen, MAX(date_time) desc, MAX(e.id) desc
它抛出此错误:
#
1056-无法在“靶场日”分组如果我从
range_day
子句中删除GROUP BY
,那么它也可以工作。但我还需要根据range_day
对结果进行分组。我该怎么做? 最佳答案
不知道你想做什么。但您可以将查询包装成子查询,而不必在GROUPBY子句中使用range_day
。然后在外部查询中按原样使用GROUPBY子句。
SELECT SUM(score) score,
type,
context, -- WARNING! Not listed in group by clause
post_id,
table_code,
comment_id,
MIN(seen) seen,
MAX(d_t) d_t,
range_day
FROM (
SELECT SUM(score) score,
MAX(id) as id,
type,
context, -- WARNING! Not listed in group by clause
post_id,
e.table_code,
comment_id,
MIN(seen) seen,
MAX(date_time) d_t,
(CASE WHEN FROM_UNIXTIME(MAX(date_time)) >= CURDATE() THEN 'today'
WHEN FROM_UNIXTIME(MAX(date_time)) >= DATE_SUB(CURDATE(), INTERVAL 1 DAY) THEN 'yesterday'
WHEN FROM_UNIXTIME(MAX(date_time)) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN 'in last week'
ELSE 'in last month'
END) as range_day
FROM `events` e
WHERE e.id IN ($ids)
GROUP BY type, post_id, e.table_code, comment_id
) sub
GROUP BY type, post_id, table_code, comment_id, range_day
ORDER BY seen, MAX(d_t) desc, MAX(id) desc
但是-您选择的不带聚合的
context
不在GROUP BY子句中列出。因此,您将从组中获得一些“随机”值。在严格模式下,查询将失败。关于mysql - 如何在GROUP BY子句上使用别名?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39358749/