按城市,省和国家的Mysql顺序

时间:2016-12-20 09:09:53

标签: mysql

Table: entity
╔════╦════════════╦═════════════╦════════════╗
║ id ║ city_id    ║ province_id ║ country_id ║
╠════╬════════════╬═════════════╬════════════╣
║  1 ║ NULL       ║ 654         ║ 12         ║
║  2 ║ 17782      ║ 654         ║ 12         ║
║  3 ║ 17782      ║ 654         ║ 12         ║
║  4 ║ 16762      ║ NULL        ║ 32         ║
╚════╩════════════╩═════════════╩════════════╝

我有三个值来查询entity表:

city_id = 17782 province_id = 654country_id = 12

现在我想按顺序提供的值对结果进行排序 city_id> province_id> COUNTRY_ID 即可。

  1. 如果city_id不为null且city_id = 17782,那么它应该在结果集中排在第一位
  2. 如果city_id为null,则它将按省_id = 654排序 假设province_id不为null
  3. 如果province_id为null,则它将回退到country_id = 12
  4. 我有这个查询无法按预期工作

    select * from entity 
    order by city_id is null, city_id <> 17782, 
    province_id is null, province_id <> 654, country_id <> 12
    

    提供以下结果集

    ╔════╦════════════╦═════════════╦════════════╗
    ║ id ║ city_id    ║ province_id ║ country_id ║
    ╠════╬════════════╬═════════════╬════════════╣
    ║  2 ║ 17782      ║ 654         ║ 12         ║
    ║  3 ║ 17782      ║ 654         ║ 12         ║
    ║  4 ║ 16762      ║ NULL        ║ 34         ║
    ║  1 ║ NULL       ║ 654         ║ 12         ║
    ╚════╩════════════╩═════════════╩════════════╝
    

    注意带有null值的province_id是第一个,而值654应该是第一个,这是因为第一个条件city_id为null

    期望的结果

    ╔════╦════════════╦═════════════╦════════════╗
    ║ id ║ city_id    ║ province_id ║ country_id ║
    ╠════╬════════════╬═════════════╬════════════╣
    ║  2 ║ 17782      ║ 654         ║ 12         ║
    ║  3 ║ 17782      ║ 654         ║ 12         ║
    ║  1 ║ NULL       ║ 654         ║ 12         ║
    ║  4 ║ 16762      ║ NULL        ║ 34         ║
    ╚════╩════════════╩═════════════╩════════════╝
    

2 个答案:

答案 0 :(得分:1)

试试这个:

ORDER BY

<=>的第一部分将所有所需的值放在结果的前面,然后其余部分按优先级城市,省份,国家/地区排序。

我使用null-safe equal operator city_id = NULL,因此province_id不会强制排除void insertBefore(list *l, void *p){ node* newNode = malloc(sizeof(node) + l->SizeOfData); memcpy(newNode->item, p, l->SizeofData); l->curent->previous->next = newNode; l->current->previous = newNode; } void insertAfter(list *l, void *p){ node* newNode = malloc(sizeof(node) + l->SizeOfData); memcpy(newNode->item, p, l->SizeofData); l->curent->next->previous = newNode; l->current->previous->next = newNode; l->current = newNode; } 排序。

答案 1 :(得分:0)

试试以下内容并告诉我们。

select * from entity 
order by 
   case when city_id = 17782 and province_id is not null then 1 
        when city_id is null and province_id = 654 then 2 
        when province_id is null and country_id = 12 then 3 
   else 4 end