mysql query to get data ordered by date, time, and name (but don't want to split common names apart under each date)
I have a MySQL query that produces this output ordered like this:
Instead I'd like the output ordered like this:
I'm not sure how to write the query so that it orders the data the way I need it. I need the data sorted by date DESC, then by time DESC, but also to chunk common 'markers_name' elements together. (I only want them chunked together for each date).
This is the query I'm using:
SELECT markers.name AS markers_name,
conditions.time AS conditions_time,
conditions.date AS conditions_date,
station.name AS station_name
FROM markers, conditions, users
WHERE conditions.markers_id = markers.id
AND (conditions.station_id = station.id)
ORDER BY date DESC, markers.name, time DESC
LIMIT 100
(P.S. I omitted showing the station_name in my output tables, but they do show up in my real query.)
EDIT: I've added some more tables in an attempt to explain the problem better. Note that "chunk" isn't really returned by the query. I just added that to help with the conversation. Each chunk has a common date.
Here is output after I tried ORDER BY date DESC , markers.name DESC , time DESC
And here is my desired output:
Compare 'Chunk 4' in the two outputs. The upper table orders by name descending. This is not desired. Marker_name 'd' has the newest information so I want it to be first. 'C' has the next newest information. 'f' has the oldest information. The next table shows the ordering that I need.
Hopefully this conveys the issue better. Can anyone开发者_运维百科 help?
EDIT 2 I tried this proposed answer: "ORDER BY date DESC, time DESC, markers.name DESC" but it didn't work.
Note that chunk 3 is ordered by time. The 'e' and 'b' rows are not grouped together.
Get the list of MAX(time)
values for every combination of (markers_id, date)
in conditions
, then join that list to the rowset you are getting from your present query, and use the MAX(time)
values for sorting:
SELECT
m.name AS markers_name,
c.time AS conditions_time,
c.date AS conditions_date,
s.name AS station_name
FROM markers m
INNER JOIN conditions c ON c.markers_id = m.id
INNER JOIN station s ON c.station_id = s.id
INNER JOIN (
SELECT
markers_id,
date,
MAX(time) AS time
FROM conditions
GROUP BY
markers_id,
date
) mx ON c.markers_id = mx.markers_id AND c.date = mx.date
ORDER BY
c.date DESC,
mx.time DESC,
m.name DESC,
c.time DESC
what happens if in your query in the ORDER BY you add DESC
for markers.name
... ORDER BY date DESC, markers.name **DESC**, time DESC LIMIT 100
?
精彩评论