I have the following mysql table
ID (int) parent_id (int) title (str) date (int - unix timestamp)
------------------------------------------------------------------------------------
252 2 Title 1 1378872876 (01. sept)
262 2 Title 2 1378870827 (02. sept)
273 3 Title 3 1378870800 (04. sept)
296 3 Title 4 1378869614 (05. sept)
301 2 Title 5 1378869384 (02. sept)
324 4 Title 6 1378868522 (02. sept)
339 3 Title 7 1378865096 (03. sept)
355 3 Title 8 1378864830 (02. sept)
365 4 Title 9 1378863323 (04. sept)
366 4 Title 10 1378863240 (02. sept)
376 2 Title 11 1378859731 (01. sept)
381 5 Title 12 1378858380 (03. sept)
388 3 Title 13 1378858080 (02. sept)
392 4 Title 14 1378857600 (04. sept)
What i want to do is to select all rows ordered by the unix timestamp (only day), but also group by parent_id. So, the SQL query should return the following:
ID (int) parent_id (int) title (str) date (int - unix timestamp)
------------------------------------------------------------------------------------
296 3 Title 4 1378869614 (05. sept)
273 3 Title 3 1378870800 (04. sept)
339 3 Title 7 1378865096 (03. sept)
388 3 Title 13 1378858080 (02. sept)
355 3 Title 8 1378864830 (02. sept)
392 4 Title 14 1378857600 (04. sept)
365 4 Title 9 1378863323 (04. sept)
366 4 Title 10 1378863240 (02. sept)
324 4 Title 6 1378868522 (02. sept)
381 5 Title 12 1378858380 (03. sept)
262 2 Title 2 1378870827 (02. sept)
301 2 Title 5 1378869384 (02. sept)
252 2 Title 1 1378872876 (01. sept)
376 2 Title 11 1378859731 (01. sept)
I have tried the following but it isn't really what i want:
SELECT
f.*,
FROM_UNIXTIME(f.post_date , '%d' ) AS day,
FROM_UNIXTIME(f.post_date , '%H' ) AS hour
FROM feeds f
WHERE f.parent_id IN (200,194,176,182,190,181,189,196,191)
GROUP BY f.parent_id
ORDER BY f.post_date DESC
LIMIT 0,100
Can this be done only with mysql or do I have to build multiple queries?
SELECT f.*
FROM feeds f
INNER JOIN (SELECT parent_id, MAX(post_date) AS Ordered GROUP BY parent_id) o
ON f.parent_id = o.parent_id
ORDER BY o.Ordered
Find latest post by parent_id, use its timestamp as first column to order by, parent_id as second ( in case of two same timestamps ) and finally by actual timestamp.
SELECT
f.*,
FROM_UNIXTIME(f.post_date , '%d' ) AS day,
FROM_UNIXTIME(f.post_date , '%H' ) AS hour
FROM feeds f
JOIN ( SELECT parent_id, MAX( post_date ) as latest_post
FROM feeds
GROUP BY parent_id ) fl
ON f.parent_id = fl.parent_id
ORDER BY fl.latest_post DESC, parent_id, f.post_date DESC
You need to tell mysql how it should aggregate the non grouped columns. When you order you can do it by the alias day or the function. ie:
ORDER BY FROM_UNIXTIME(f.post_date , '%d' )
or
ORDER BY DAY
the alias DAY might be a reserved keyword, so I would consider to change it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.