如何使MYSQL查询结果ORDER BY条件顺序?

时间:2010-04-10 09:49:11

标签: mysql sql-order-by

我的查询字符串如下:

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

对于结果,我希望首先返回符合condition1的条目,然后返回符合condition2的条目,最后返回符合condition3的条目。有什么想法吗?

2 个答案:

答案 0 :(得分:28)

要按照您想要的顺序进行排序,请在ORDER BY中使用您的条件,但在它们之后使用DESC

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

如果这不起作用,因为您的查询更复杂,那么您可以使用布尔逻辑将查询(A OR B OR C) AND D更改为(A AND D) OR (B AND D) OR (C AND D),然后您可以使用以下查询:

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

这里不需要AND static,因为所有行都返回它,但是在一个更复杂的例子中(你还返回一些非静态的行),你就必须这样做。

答案 1 :(得分:9)

这应该有效:

ORDER BY condition1, condition2, condition3

例如

ORDER BY (weight > 500), (height > 3), (height < 2)