简体   繁体   English

选择并在两列MySQL上排序

[英]Select and sort on two columns MySQL

So, my code looks like this 所以,我的代码看起来像这样

mysql_query("SELECT * FROM threads WHERE forum_id = '$id' ORDER BY type,posted DESC") or                                 
die(mysql_error());

"posted" is the value of time() and is selected decreased to put the latest one at the top. “ posted”是time()的值,并选择减少以将最新的值放在顶部。 "type" contains either 1 or 2. If it's 2, the thread is pinned. “类型”包含1或2。如果为2,则将线程固定。 Currently, it sorts after posted but those which should be at the top (pinned) are at the bottom. 目前,它在发布后进行排序,但应在顶部(固定)的在底部。 Is there any fix that I'm missing? 我有没有解决的方法?

Try: ORDER BY type DESC, posted DESC 尝试:按ORDER BY type DESC, posted DESC

By default, it sorts ascending. 默认情况下,它升序排列。 You need to specify the order for both fields you would like to order by. 您需要为两个字段指定排序顺序。

ORDER BY Documentation 按文件订购

Don't forget that the asc/desc in an order by applies to each individual field, not the entire order by clause. 不要忘记order by中的asc / desc适用于每个单独的字段,而不适用于整个order by子句。

ORDER BY type DESC, posted ASC

MySQL can also accept arbitrary logic for order by, so for more complicated sort requirements, you could have something like MySQL还可以接受任意逻辑进行排序,因此对于更复杂的排序要求,您可能会遇到类似

ORDER BY IF(type=2, 0, 1) AS pinned ASC, posted DESC

as long the arbitrary logic returns something that's trivially sortable (eg a number or a string), there's no limit to how complicated the sorting can be. 只要任意逻辑返回可以被平凡排序的内容(例如数字或字符串),排序的复杂程度就没有限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM