为什么这个查询不起作用?是因为 order by 和 group by 的组合吗?
一个表包含广告,另一个表包含订阅,第三个表包含服务,第四个表是服务和位置之间的多对多关系(位置是应显示广告的位置)。
我想要的是先对存储在广告表中位置 2 的广告进行排序,然后是那些没有定义位置的广告,然后是位置 1(此顺序是通过编程生成的)
广告表:
id、名称、subscription_id
订阅表:
subscription_id、service_id、日期、付费等...
service_locations 表:
service_id、location_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/