I hope you will be able to help me, this has been giving me headaches 😀
First, a bit of context:
Using the following table and data:
+-------------+---------+-------------+
| 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 |
+-------------+---------+-------------+
What I’d lke to do is to print this out to a table with the host_name cell that spans the right amount of rows, a bit like so:
+-------------+---------+-------------+
| host_name | service | last_change |
+-------------+---------+-------------+
| | PING | 1327004398 |
| test.com | HTTP | 1327004536 |
| | MYSQL | 1327004392 |
+-------------+---------+-------------+
I am already able to do this, using a query that looks like this:
SELECT
host_name,
group_concat(service SEPARATOR '|') as service,
group_concat(last_change SEPARATOR '|') as last_change,
FROM table
GROUP BY host_name
And then by doing some manipulations (exploding results where pipes are found).
The problem I have:
I’d like to do the same thing but sort the results based on last_change. I tried to do the following:
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
But it doesn’t seem to work. Changing the DESC to ASC doesn’t even change the results I get.
If I run the subquery that orders the results by itself, I get the expected results except the results arent grouped by host_name (obviously since it lacks the group_concat and group by statements).
Any ideas ?
I appreciate it A LOT.
I didn’t get exactly what you’re trying to do here. Do you want results inside the group ordered, or the whole resultset?
Try this for the first case:
And this for second: