Hello. There is a table id, title, sort.

In table 50 values. Of these, 20 values ​​are filled with the sort field from 1 to 20, the others do not, the value is 0. How to sort the table by the following condition. We first sort by sort, and then by title sort with a value of 0

2 answers 2

select * from table order by if(sort=0,2,1), sort, title 

if specifies a condition, if sort <> 0, then it returns 1, if it is equal to - then 2. thus, records with sort <> 0 are the first.

  • You can explain what sort = 0,2,1 - duddeniska is sep
 SELECT * FROM table ORDER BY sort = 0, title +-------+------+ | title | sort | +-------+------+ | a | 1 | | b | 2 | | b | 3 | | a | 0 | | b | 0 | | g | 0 | | r | 0 | | z | 0 | +-------+------+