简体   繁体   English

在MySQL中按多列排序

[英]Order by in MySQL for multiple columns

I've four columns sale date 4 , sale date 3 , sale date 2 , sale date in my table which are all sale dates. 我的表中有四个列,分别是sale date 4sale date 3sale date 2sale date ,这些都是销售日期。 While displaying in page sale date 4 is given first priority if it is not empty we are displaying it and if it is empty then comes sale date 3 and then sale date 2 and then sale date . 当页面中显示sale date 4如果它不为空,则显示为优先级,如果显示为空,则显示sale date 3 ,然后是sale date 2 ,然后是sale date

My problem is while sorting the results. 我的问题是在对结果进行排序时。

When is run the query with order by 什么时候运行查询

order by 
isnull(`sale date 4`), trim(`sale date 4`) , 
isnull(`sale date 3`), trim(`sale date 3`) , 
isnull(`sale date 2`), trim(`sale date 2`) , 
isnull(`sale date`), trim(`sale date`) asc

I'm getting results as follows 我得到如下结果

**sale date 4** | **sale date 3**  | **sale date 2** | **sale date**
--------------------------------------------------------------------
2013-01-24      | 2013-01-24       | 2013-01-24      | 2013-01-24    
2013-01-31      | 2013-01-31       | 2013-01-31      | 2012-11-30    
2013-02-01      | 2013-02-01       | 2013-02-01      | 2013-02-01    
2013-03-08      | 2013-03-08       | 2013-03-08      | 2013-03-08    
----NULL----    | ----NULL----     | 2013-02-28      | 2012-11-02    
----NULL----    | ----NULL----     | ----NULL----    | 2013-02-28

And when I display in the view it will be as follows 当我在视图中显示时,将如下所示

1. Sale date = 2013-01-24
2. Sale date = 2013-01-31
3. Sale date = 2013-02-01
4. Sale date = 2013-03-08
5. Sale date = 2013-02-28
6. Sale date = 2013-02-28

But what I need is 但是我需要的是

1. Sale date = 2013-01-24
2. Sale date = 2013-01-31
3. Sale date = 2013-02-01
4. Sale date = 2013-02-28
5. Sale date = 2013-02-28
6. Sale date = 2013-03-08

How can I accomplish this? 我该怎么做?

isnull(column) simply returns true or false . isnull(column)仅返回truefalse This results in the first 4 records being the first 4 results ( true > false ) and record 5 and 6 being the last two results. 这导致前4个记录是前4个结果( true > false ),记录5和6是后两个结果。 The last two results are then sorted by sale date 4 ( NULL in both columns) up to sale date 1 , but they remain the last two items in the ordered list. 然后,最后两个结果按sale date 4排序(两个列均为NULL ),直到sale date 1 ,但它们仍是已排序列表中的最后两个项目。

What you want to do is probably something like this: 您想要做的可能是这样的:

.. ORDER BY IFNULL(`sale date 4`, IFNULL(`sale date 3`,
            IFNULL(`sale date 2`, `sale date 1`)))

You could order by: 您可以通过以下方式订购:

coalesce(`sale date 4`, `sale date 3`, `sale date 2`, `sale date`)

COALESCE returns the first non-NULL value, eg. COALESCE返回第一个非NULL值,例如。

coalesce(1,2,3,4)             returns 1
coalesce(null,2,3,4)          returns 2
...
coalesce(null,null,null,null) returns null

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

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