【问题标题】:How to make MYSQL query results ORDER BY conditions order?如何使MYSQL查询结果ORDER BY条件排序?
【发布时间】:2010-04-10 09:49:10
【问题描述】:

我的查询字符串是这样的:

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 的条目。有什么想法吗?

【问题讨论】:

  • 您的情况是否不同?如果不是,如果一个条目满足多个条件怎么办?例如,如果条目满足条件1和3,与满足条件1和2的条目相比,它应该如何排序?
  • 这里没有限制,所以我想也许先见面先回?

标签: mysql sql-order-by


【解决方案1】:

要按您想要的顺序进行排序,请在 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 在这里不是必需的,因为所有行都会返回它,但在更复杂的示例中(您还返回一些非静态的行),则必须以这种方式进行。

【讨论】:

  • 条件如何(我的查询字符串已更新)类似于 table.id = 123 ?我试过 ORDER BY 句子,但没有效果。
  • @Relax:我之前给出的示例可以正常工作。无论如何,我已经更新了它,因为我猜您的实际查询比您允许我们知道的要复杂。
  • 你绝对正确!即使条件类似于 table.id=123,我也没有意识到 DESC 是必需的。现在我添加了它,它就像一个魅力,非常感谢!
  • 为什么顺便需要DESC?
  • 因为 TRUE 等于 1,而 FALSE 是 0。如果你想要真正的值,你有降序。
【解决方案2】:

这应该有效:

ORDER BY condition1, condition2, condition3

例如

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

【讨论】:

  • 谢谢,但它不起作用,可能是因为我的实际查询字符串更复杂,我更新了它
猜你喜欢
  • 1970-01-01
  • 2015-01-07
  • 2011-12-06
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多