我有这样的查询:
SELECT
result.ip,
ips.ipStatus,
result.quantity,
result.clickDates,
FROM
ips
INNER JOIN
(
SELECT
visits.ip,
count(visits.ip) AS quantity,
GROUP_CONCAT(clicks.clickDate) AS clickDates,
FROM
visits
INNER JOIN
clicks
ON visits.id = clicks.id
WHERE
clicks.clickDate BETWEEN 1 AND 10
GROUP BY
visits.ip
ORDER BY
null
) AS result
ON ips.ip = result.ip LIMIT 6, 2
它产生如下结果表:
ip | status | quantity | date
1.1.1.1 ok 3 555, 557, 558
2.2.2.2 ok 1 657
我的日期存储在.ms(BIGINT)中。我的目标是要ORDER BY
与DESC
约会。我想最新的ips将位于顶部。因此,我正在尝试更改ORDER BY
上的ORDER BY clicks.clickDate DESC
。但这给了我一个错误:
ORDER BY子句的表达式#1不在GROUP BY子句中,并且 包含非聚合列
所以我有两个问题:
如果我在clicks.clickDate列上使用ORDER BY
,是否可以GROUP_CONCAT
?
也许有一种方法可以只显示clicks.clickDate在GROUP_CONCAT
之后的最后一个值?
答案 0 :(得分:1)
对于主查询order by
,您可以尝试在GROUP_CONCAT
中添加MAX(clicks.clickDate)
并添加一列clickDate
,以在组中获得order by
的最大值。
SELECT
result.ip,
ips.ipStatus,
result.quantity,
result.clickDates,
FROM
ips
INNER JOIN
(
SELECT
visits.ip,
count(visits.ip) AS quantity,
GROUP_CONCAT(clicks.clickDate ORDER BY clicks.clickDate desc) AS clickDates,
MAX(clicks.clickDate) maxDt
FROM
visits
INNER JOIN
clicks
ON visits.id = clicks.id
WHERE
clicks.clickDate BETWEEN 1 AND 10
GROUP BY
visits.ip
) AS result
ON ips.ip = result.ip
ORDER BY maxDt DESC
LIMIT 6, 2
答案 1 :(得分:1)
请尝试按每个记录中的最大单击日期进行排序。请注意,我们需要将文本日期数值投射为实际整数,以便排序正常进行。
SELECT
r.ip,
i.ipStatus,
r.quantity,
r.clickDates,
FROM ips i
INNER JOIN
(
SELECT
visits.ip,
count(visits.ip) AS quantity,
GROUP_CONCAT(clicks.clickDate ORDER BY clicks.clickDate desc) AS clickDates,
MAX(CAST clicks.clickDate AS UNSIGNED) maxDt
FROM
visits
INNER JOIN
clicks
ON visits.id = clicks.id
WHERE
clicks.clickDate BETWEEN 1 AND 10
GROUP BY
visits.ip
) r
ON i.ip = r.ip
ORDER BY maxDt DESC
LIMIT 6, 2;