【发布时间】:2016-06-11 14:15:11
【问题描述】:
为什么这个查询不起作用?是因为 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 |
+----+-----------+
【问题讨论】:
标签: mysql join group-by sql-order-by case