We have such table in MySQL: id - int; title - varchar; hd - tinyint; source - tinyint; active - tinyint;
How do i get data from database with such sorting:
1. hd >= 3 AND source <> 5
2. hd >= 3 AND source = 5
3. hd = 2
4. other, i.e. hd < 2
Please show me how to do it properly and one sql query?
Thank you.
The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Summary. Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order. The ORDER BY clause is evaluated after the FROM and SELECT clauses.
Using ORDER BY to sort on two columns In such a case, MySQL treats the first field as primary and the latter as secondary. Therefore, it first sorts the primary and then the second one. Hence, in this example, we'll demonstrate ORDER BY on two columns, one field as ASC, and another DESC.
If you want to select records from a table but would like to see them sorted according to a given column, you can simply use the ORDER BY clause at the end of a SELECT statement.
select * from your_table
order by case when hd >= 3 AND source <> 5 then 1
when hd >= 3 AND source = 5 then 2
when hd = 2 then 3
else 4
end
Try this:
select *
from table_name
order by case when hd >= 3 AND source <> 5 then 1
when hd >= 3 AND source = 5 then 2
when hd = 2 then 3
else 4
end
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