我希望你能帮助我,这让我感到头痛:D
首先,一点上下文:
使用下表和数据:
+-------------+---------+-------------+
| host_name | service | last_change |
+-------------+---------+-------------+
| test.com | PING | 1327004398 |
| test.com | HTTP | 1327004536 |
| test.com | MYSQL | 1327004392 |
| test2.com | PING | 1327127720 |
| test2.com | HTTP | 1327004391 |
| test3.com | PING | 1327213842 |
| test4.com | PING | 1327004368 |
+-------------+---------+-------------+
我要做的是将其打印到一个表中,其中host_name单元格跨越了正确的行数,有点像这样:
+-------------+---------+-------------+
| host_name | service | last_change |
+-------------+---------+-------------+
| | PING | 1327004398 |
| test.com | HTTP | 1327004536 |
| | MYSQL | 1327004392 |
+-------------+---------+-------------+
我已经能够使用如下所示的查询来执行此操作:
SELECT
host_name,
group_concat(service SEPARATOR '|') as service,
group_concat(last_change SEPARATOR '|') as last_change,
FROM table
GROUP BY host_name
然后通过做一些操作(爆炸结果发现管道)。
我遇到的问题:
我想做同样的事情,但是根据last_change对结果进行排序。我试着做以下事情:
SELECT
host_name,
group_concat(service SEPARATOR '|') as service,
group_concat(last_change SEPARATOR '|') as last_change,
FROM
(
SELECT * FROM table ORDER BY last_change DESC
) as tmp_table
GROUP BY host_name
但它似乎不起作用。将DESC更改为ASC甚至不会改变我得到的结果。
如果我运行自定义结果的子查询,我会得到预期的结果,但结果不是按host_name分组的(显然因为它缺少group_concat和group by语句)。
有什么想法吗?
我很感激。
答案 0 :(得分:0)
我没有得到你在这里想做的事情。您是否希望在订购的组内或整个结果集中获得结果? 试试第一种情况:
SELECT
host_name,
group_concat(service ORDER BY last_change DESC SEPARATOR '|') as service,
group_concat(last_change ORDER BY last_change DESC SEPARATOR '|') as last_change
FROM table
GROUP BY host_name
这是第二个:
SELECT
host_name,
group_concat(service SEPARATOR '|') as service,
group_concat(last_change SEPARATOR '|') as last_change
FROM table
GROUP BY host_name
ORDER BY table.last_change
答案 1 :(得分:0)
group_concat参数中有ORDER BY说明符:
SELECT
host_name,
group_concat(service SEPARATOR '|') as service,
group_concat(last_change ORDER BY last_change SEPARATOR '|') as last_change,
FROM table
GROUP BY host_name