mysql - 在 MySQL 中使用 Case 加入 Group By 和 Order

标签 mysql join group-by sql-order-by case

为什么这个查询不起作用?是因为 order by 和 group by 的组合吗?

一个表包含广告,另一个表包含订阅,第三个表包含服务,第四个表是服务和位置之间的多对多关系(位置是应显示广告的位置)。

我想要的是先对存储在广告表中位置 2 的广告进行排序,然后是那些没有定义位置的广告,然后是位置 1(此顺序是通过编程生成的)

广告表:
id、名称、subscription_id

订阅表:
subscription_id、service_id、日期、付费等...

service_locations 表:
service_idlocation_id

正如您所见,在这种情况下有第四个表,但这并不重要


查询:

select adverts.id, GROUP_CONCAT(service_locations.location_id) AS locations from adverts 
    left join subscriptions 
        on adverts.subscription_id = subscriptions.id
    left join service_locations 
        on service_locations.service_id = subscriptions.service_id
    group by adverts.id
    order by case service_locations.location_id 
        when 2 then 1 
        when 1 then 3 
        else 2 
    end


预期结果:

+----+-----------+
| id | locations |
+----+-----------+
|  1 | 2         |
|  3 | 1,2       |
|  2 | null      |
+----+-----------+


我实际得到的(行中的第三个位置为 2,但它位于 null 之后):

+----+-----------+
| id | locations |
+----+-----------+
|  1 | 2         |
|  2 | null      |
|  3 | 1,2       |
+----+-----------+

最佳答案

当您使用group by时,不在group by中的所有列都应该具有聚合函数。所以,我认为你的意图是这样的:

select a.id, GROUP_CONCAT(sl.location_id) AS locations
from adverts a left join
     subscriptions s
     on a.subscription_id = s.id left join
     service_locations sl
     on sl.service_id = s.service_id
group by a.id
order by max(case sl.location_id 
               when 2 then 1 
               when 1 then 3 
               else 2 
             end);

我不确定 max() 是否是您真正需要的,但您确实需要一个聚合函数。这具体产生了问题中的输出:

order by (case min(sl.location_id)
               when 2 then 1 
               when 1 then 2
               else 3
           end);

关于mysql - 在 MySQL 中使用 Case 加入 Group By 和 Order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35684334/

相关文章:

Mysql 在 date_time 字段中按天分组

MySQL LEFT JOIN 与 GROUP BY 和聚合运算符阻塞

python - 从 pandas dataframe groupby 中提取带有计数的新列

php - 带有 LOAD DATA LOCAL INFILE 的 MySQL 错误消息

mysql - MS-ACCESS 如何创建查询以选择所有包含与另一个查询匹配的字段的记录?

php - 如何将传递的字符串匹配到检查 mysql 数据库的 php 函数

mysql - 如果 schema.rb 不存在,为什么 Cucumber 会删除表?

mysql - 连接两个表 MySQL 即使有索引也很慢

Linux - 加入 2 个 CSV 文件

mysql - 为什么 CodeIgniter Active Record 和 phpMyAdmin 给出不同的结果?