2012-01-22 115 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