Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query with complex sorting

Tags:

mysql

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.

like image 538
universal_mind Avatar asked Nov 25 '13 16:11

universal_mind


People also ask

How do I sort a MySQL query?

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.

How do I sort multiple columns in MySQL?

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.

Can we sort by two columns in MySQL?

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.

How do I sort by alphabetical order in MySQL?

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.


2 Answers

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
like image 167
juergen d Avatar answered Oct 06 '22 21:10

juergen d


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
like image 34
Rahul Tripathi Avatar answered Oct 06 '22 23:10

Rahul Tripathi