2012-01-22 78 views
2

我希望你能帮助我,这已经让我选择头痛的事:dMySQL的:从排序结果

首先,一些背景:

使用下面的表和数据:

+-------------+---------+-------------+ 
| 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语句)。

任何想法?

我很欣赏它很多。

+1

这真的不是目的(我的)SQL。 MySQL旨在存储数据 - 显示和呈现它应该用外部语言完成。你可以毫不费力地用php,C#,java来做这件事......但是,这对于SQL熟练者来说是一个有趣的练习:] – Konerak

回答

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 
+0

我试图让每个组中的结果排序,然后定义组。 – mexicanpsycho

+0

好吧,所以我尝试了第二个查询,它几乎似乎做了伎俩。他们几乎(!)排序正确,这很奇怪。我会尽力与之合作。谢谢 ! – mexicanpsycho

+0

只是想说,第二个解决方案结束了我工作得很好。谢谢 ! – mexicanpsycho

0

有ORDER BY符在GROUP_CONCAT参数:

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 
+0

感谢您的提示,我试过了,但它似乎没有对结果产生影响。我试过把ORDER BY last_change DESC和ASC和结果完全一样。 – mexicanpsycho