I have a column "available" which either returns "yes" or for instance "30 min".
To sort this table we have found out that this works as intended where "Yes" comes first, and the "30 min" comes after.
order by available + 0 asc
Even though this works we do not know why we have to put +0 to the column. Can someone elaborate?
Edit: This is an example on a query
Note that all where clauses are not here, and the if(x is null) is to return something if there is no result aka null value.
select distinct r.rname, if(b.stime is null, 'Yes', 'Yes') as available, r.mperson
from Rooms r left outer join Bookings b using (rname)
union all
select b.rname, concat(minute(timediff(b.etime, '$sdate')), ' min') as available, r.mperson
from Bookings b inner join Rooms r using(rname)
order by available + 0 asc, rname asc
You're implicitely converting the available
value to a number, as you can see by trying
select "30 minutes" + 0; ==> returns 30
select "2 hours" + 0; ==> returns 2
select "yes" + 0; ==> returns 0
This makes "yes"
(or any string not starting by a number) the first returned value instead of the last one.
This does change the order but this feels hacky and is less efficient than using a pure numeric field (which could be indexed).
More generally you always should define your schema such as to have precise non polymorphic fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With