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

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值