按多种条件排序

时间:2013-09-09 14:32:25

标签: mysql sql filtering distinct

即时通讯非常棒,这变得不可知(这是一个字吗?)

等级是按时间但是......

time done with ( A=0 ) AND ( B=0 ) beat everyone
time done with ( A=0 ) AND ( B=1 ) beat everyone with ( A=1 )
time done with ( A=1 ) AND ( B=0 ) beat everyone with ( A=1 + B=1 )

排名示例(track = desert)

pos--car------time---A----B
1.---yellow----90----No---No
2.---red-------95----No---No
3.---grey-----78-----No---Yes
4.---orange--253---No---Yes
5.---black----86----Yes---No
6.---white----149---Yes---No
7.---pink-----59----Yes---Yes
8.---blue-----61----Yes---Yes

为了使它更糟糕,该表接受同一辆车的多个记录

这是条目

create table `rank`
(
`id` int not null auto_increment,
`track` varchar(25) not null,
`car` varchar(32) not null,
`time` int not null,
`a` boolean not null,
`b` boolean not null,
primary key (`id`)
);
insert into rank (track,car,time,a,b) values
 ('desert','red','95','0','0'),
 ('desert','yellow','89','0','1'),
 ('desert','yellow','108','0','0'),
 ('desert','red','57','1','1'),
 ('desert','orange','120','1','0'),
 ('desert','grey','85','0','1'),
 ('desert','grey','64','1','0'),
 ('desert','yellow','90','0','0'),
 ('desert','white','92','1','1'),
 ('desert','orange','253','0','1'),
 ('desert','black','86','1','0'),
 ('desert','yellow','94','0','1'),
 ('desert','white','149','1','0'),
 ('desert','pink','59','1','1'),
 ('desert','grey','78','0','1'),
 ('desert','blue','61','1','1'),
 ('desert','pink','73','1','1');
请帮忙吗? :P

ps:抱歉示例表

1 个答案:

答案 0 :(得分:1)

要优先a,然后b,然后time,请使用order by b, a, time

您可以使用not exists子查询仅选择每辆车的最佳行。

最后,您可以使用MySQL的变量添加Pos列,例如@rn := @rn + 1

示例查询:

select  @rn := @rn + 1 as pos
,       r.*
from    rank r
join    (select @rn := 0) init
where   not exists
        (
        select  *
        from    rank r2
        where   r.car = r2.car
                and (
                    r2.a < r.a
                    or (r2.a = r.a and r2.b < r.b)
                    or (r2.a = r.a and r2.b = r.b and r2.time < r.time)
                )
        )
order by
        b
,       a
,       time

See it working at SQL Fiddle.