问题
This is my first time I'm asking a question, and English is not my native language. I apologize for any misspelling or misbehaving beforehand. Now to my question: I have a table looking like this. (image 1) 1. Every booked time is half an hour long 2. There are always booking_date, hour and minute 3. Some rows have got delivery_date, some hasn’t yet 4. Delivery_date are always AFTER booking_date
unordered table
If the day being printed out is for example (2018-12-01), I want the table to be ordered by the date being viewed (2018-12-01) either it is the booking_date OR delivery_date, which comes first. AND should be ordered by (hour, minute) of each. Like below: (image 2)
Ideal ordered
AS you can see it jumps from row 01 to 08 and then back to 05, then to 02. It’s because it has to be ordered by hour and minute. And yet, the delivery_date has such priority that it jumps in between the rows (like row 05)
I’ve tried this SQL:
SELECT * FROM booking WHERE booking_date=$b_date OR DATE(delivery_date)=$b_date ORDER BY hour, minute ASC, HOUR(delivery_date), MINUTE(delivery_date) ASC
This will give me the booking_date ordered correctly by hour, minute, but the delivery_date is not correctly ordered
Then I have also searched, found on Stackoverflow.com and tried this one:
SELECT * FROM booking WHERE booking_date=$b_date OR DATE(delivery_date)=$b_date ORDER BY CASE WHEN booking_date=$b_date THEN hour, minute WHEN DATE(delivery_date)=$b_date THEN HOUR(delivery_date), MINUTE(delivery_date) END ASC
This gives me the following error:
check the manual that corresponds to your MySQL server version for the right syntax to use near ' minute WHEN DATE(delivery_date)=$b_date THEN HOUR(delivery_date), MINUTE(delivery_date) END' at line 1
and that is the comma after ”hour”. I take it, it doesn’t like the comma, so I can’t use 2 columns for ORDER BY. When I use only one column it works, but the minutes will be wrong. Is there a way to use 2 columns in ORDER BY?
回答1:
The THEN
clause may only specify one value. Instead you can order by minutes:
SELECT *
FROM booking
WHERE booking_date=$b_date OR DATE(delivery_date)=$b_date
ORDER BY CASE WHEN booking_date=$b_date
THEN hour * 60 + minute
WHEN DATE(delivery_date)=$b_date
THEN HOUR(delivery_date) * 60 + MINUTE(delivery_date)
END ASC
来源:https://stackoverflow.com/questions/53652527/sorting-table-by-different-cols-depending-on-what-happens-to-another-column