I am using GROUP BY to only select one row for all entries that share the same 'cat_no' value, because GROUP BY retrieves a random row I need to use ORDER BY ABS(track) to ensure it selects the row that is track number "1" in the database. However once I have this set of results I need to actually have the final order by 'date' another field in the DB, but I can't seem to order twice.
SELECT * FROM cds
WHERE genre='rock'
GROUP BY cat_no
ORDER BY date DESC,ABS(track) DESC
LIMIT 0,3
Sql is only honouring the first order by clause, in this case 'date', if I swap them around then 'track' is used and 'date' ignored
Table
genre cat_no track date
rock 001 1 09323123
rock 001 2 09323123
rock 001 bundle 09323123
rock 002 1 09323123
rock 002 2 09323123
rock 002 bundle 09323123
rock 003 1 09323123
rock 003 2 09323123
rock 003 bundle 09323123
If you always want track 1, you don't need to group:
SELECT * FROM cds
WHERE genre = 'rock' AND track = 1
ORDER BY date DESC
LIMIT 0, 3
If you want the first track (not necessarily track 1), then you need a subquery:
SELECT * FROM cds c
WHERE genre = 'rock'
AND track = (
SELECT MIN(track) FROM cds innerq
WHERE innerq.cat_no = c.cat_no
LIMIT 1
)
ORDER BY date DESC
LIMIT 0, 3
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.