简体   繁体   English

如何对字段为零的sql查询排序?

[英]how to sort sql query with fields with a zero last?

I have a sql table that I am sorting by expires time which is a unix timestamp, if there is no expire time I just set that to 0, the problem I am having is when i sort this column in ASC (so expiring first) the rows with a 0 for expiry show up first, is there a way i can get them to show up last? 我有一个sql表,我按照过期时间排序,这是一个unix时间戳,如果没有过期时间我只是将其设置为0,我遇到的问题是当我在ASC中排序这个列时(首先到期)带有0的到期行首先显示,有没有办法让我最后显示它们?

Here is an example query: 这是一个示例查询:

SELECT s.`id`, s.`info`, s.`website`, s.`date`, s.`provider_id`, s.`drmfree`, 
       s.`steam`, s.`desura`, s.savings, s.pwyw, s.pounds, s.dollars, s.euros, 
       s.has_screenshot, s.screenshot_filename, s.`expires`, p.`name` 
FROM `game_sales` s 
      LEFT JOIN `game_sales_provider` p 
            ON s.provider_id = p.provider_id   
WHERE s.`accepted` = 1 AND s.provider_id = ? 
ORDER BY s.expires ASC

the simpliest way, boolean arithmetic. 最简单的方法,布尔算术。

ORDER BY s.expires = 0, s.expires

This works only in mysql, however. 但是,这仅适用于mysql。

When the value of s.expires is 0 , then s.expires值为0 ,则

 0 = 0 --> returns true or 1

otherwise, if not equal to zero, let's say 1 否则,如果不等于零,那么就说1

 1 = 0 --> returns false or 0

if you want to work on other RDBMS as well, use CASE 如果您也想使用其他RDBMS,请使用CASE

 ORDER BY CASE WHEN s.expires = 0 THEN 1 ELSE 0 END, s.expires

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

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