Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make MYSQL query results ORDER BY conditions order?

My query string is like:

SELECT ... FROM maintable
LEFT JOIN table1 on (maintable.id = table1.idx)
LEFT JOIN table2 on (table1.idy = table2.idy)
LEFT JOIN table3 on (table2.idz = table3.idz)
WHERE (condition1 OR condition2 OR condition3)
AND maintable.status = static

//condition1 & condition2 & condition3 are kind of
table3.idz = 101, table3.idz = 3, maintable.id IN (1,2,3,4), and so on

For the results I want entries that meet condition1 to be returned first, then entries that meet condition2, and finally entries that meet condition3. Any ideas?

like image 784
Edward Avatar asked Apr 10 '10 09:04

Edward


People also ask

How do you get query results in the same order as given in clause?

in php u can do it like : <? php $my_array = array (3,6,1,8,9) ; $sql = 'SELECT * FROM table WHERE id IN (3,6,1,8,9)'; $sql .

How do I sort MySQL results?

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 you write a query for ORDER BY?

Syntax. SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC];


2 Answers

To get the sorting in the order you want, use your conditions in the ORDER BY, but use DESC after them.

SELECT * FROM person WHERE (condition1 OR condition2 OR condition3) AND maintable.status = static ORDER BY     condition1 DESC,     condition2 DESC,     condition3 DESC 

If this doesn't work because your query is more complex, then you can use boolean logic to change your query (A OR B OR C) AND D into (A AND D) OR (B AND D) OR (C AND D) then you can use the following query:

SELECT * FROM person WHERE (condition1 OR condition2 OR condition3) AND maintable.status = static ORDER BY     condition1 AND static DESC,     condition2 AND static DESC,     condition3 AND static DESC 

The AND static is not necessary here because all rows return it, but in a more complex example (where you also return some rows which are not static) then you would have to do it in this way.

like image 193
Mark Byers Avatar answered Sep 24 '22 18:09

Mark Byers


This should work:

ORDER BY condition1, condition2, condition3

for example

ORDER BY (weight > 500), (height > 3), (height < 2)
like image 32
Pekka Avatar answered Sep 24 '22 18:09

Pekka