首先用空字符串对结果进行排序

时间:2019-07-11 10:39:11

标签: mysql database

我有这张locations桌子:

+----+-----------+------------+----------+
| id |  country  |   state    |   city   |
+----+-----------+------------+----------+
|  1 |  US       | Georgia    |  Atlanta |
|  2 |  US       | California |          |
|  3 |  US       |            |          |
|  4 |  Canada   |  Ontario   |          |
|  5 |  Canada   |  Manitoba  | Winnipeg |
|  6 |  Canada   |            |          |

我想创建一个查询,但是无法正确构建我的ORDER BY。这是我想要的结果:

+----+-----------+------------+----------+
| id |  country  |   state    |   city   |
+----+-----------+------------+----------+
|  6 |  Canada   |            |          |
|  3 |  US       |            |          |
|  4 |  Canada   | Ontario    |          |
|  2 |  US       | California |          |
|  5 |  Canada   | Manitoba   | Winnipeg |
|  1 |  US       | Georgia    | Atlanta  |

基本上,这是我要遵循的优先事项:

  1. 国家/地区列表。字母顺序。
  2. 状态列表。字母顺序。
  3. 城市列表。字母顺序。

此查询似乎未考虑空列(我在locations表中未使用NULL):

SELECT * FROM locations
ORDER BY 
    country,state,city  

3 个答案:

答案 0 :(得分:1)

尝试以下ORDER BY子句:

SELECT *
FROM locations
ORDER BY
    CASE WHEN state = '' AND city = '' THEN 0
         WHEN city = '' THEN 1
         ELSE 2 END,
    country,
    state,
    city;

此排序逻辑首先放置缺少州和城市的那些记录。接下来是仅缺少城市的记录,最后是所有三个字段的数据都不为空的记录。

答案 1 :(得分:1)

对于8.0之前的版本...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,country VARCHAR(20) NOT NULL
,state VARCHAR(20) NULL
,city VARCHAR(20) NULL
);

INSERT INTO my_table VALUES
(1,'US','Georgia','Atlanta'),
(2,'US','California',NULL),
(3,'US',NULL,NULL),
(4,'Canada','Ontario',NULL),
(5,'Canada','Manitoba','Winnipeg'),
(6,'Canada',NULL,NULL);

SELECT id
     , country
     , state
     , city 
  FROM 
     ( SELECT x.*
            , CASE WHEN @prev=country THEN @i:=@i+1 ELSE @i:=1 END i
            , @prev:=country 
         FROM my_table x
            , (SELECT @prev:=null,@i:=0) vars 
        ORDER 
           BY country
            , city
            , state
     ) a 
 ORDER 
    BY i
     , country;
+----+---------+------------+----------+
| id | country | state      | city     |
+----+---------+------------+----------+
|  6 | Canada  | NULL       | NULL     |
|  3 | US      | NULL       | NULL     |
|  4 | Canada  | Ontario    | NULL     |
|  2 | US      | California | NULL     |
|  5 | Canada  | Manitoba   | Winnipeg |
|  1 | US      | Georgia    | Atlanta  |
+----+---------+------------+----------+

答案 2 :(得分:1)

select *
from locations
order by 
  state <> '',
  city  <> '',
  country,
  state,
  city

db-fiddle

请注意,在MySQL中,布尔表达式返回0(对于FALSE)或1(对于TRUE)。这意味着对于空的state字符串state <> ''将返回0,因此首先排序。