强制分组以保持行的原始顺序

时间:2016-03-15 10:55:33

标签: mysql group-by sql-order-by

我有这样的查询结果:

24
1
24
11
11
11
13
24
24
11
24
11
24
11
11
13
24
24
11
11
13
21
21
11
11
11
11
11
7
11
11

我需要对此结果进行分组,但如果我只是按此ID分组,则mysql也会命令它:

1
2
3
4

我想要的是:

24
1
11
13
21

。 。

有可能吗?

完整的查询是这个,基本上它根据给定的坐标计算最近的业务内部路线:

select * from (select dr.*  from drivers_route dr inner join businesses_drivers_route bdr on dr.id_drivers_route = bdr.fk_id_drivers_route inner join  (select * from (select b.idbusiness, 
       b.trading_as,  
       111.1111 *
       DEGREES(ACOS(COS(RADIANS(53.33841959999999))          * COS(RADIANS(b.latitude))
         * COS(RADIANS(-6.2876401 - b.longitude))
         + SIN(RADIANS(53.33841959999999))
         * SIN(RADIANS(b.latitude)))) AS distance_in_km from business b inner join business_category bc on bc.fk_idbusiness = b.idbusiness where b.status_reg = 'A'   and bc.status_reg = 'A'   and bc.fk_idcategory=44) as b_dist order by b_dist.distance_in_km) as b_ord on b_ord.idbusiness = bdr.fk_id_bus_destination) as r_ord;

1 个答案:

答案 0 :(得分:1)

您可以通过在查询中添加计数器来执行此操作:

SET @ c = 0; 选择my_field,(@ c:= @c +1)作为c FROM my_table组by my_field 按c顺序;

但正如Strawberry所说,拥有一个独特的主键是很好的,所以你可以使用它。