gpt4 book ai didi

mysql - 按多个条件排序

转载 作者:行者123 更新时间:2023-11-29 00:26:26 31 4
gpt4 key购买 nike

我很菜鸟,这变得无法用谷歌搜索(这是一个词吗?)

排名是按时间排序的,但是..

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:对示例表感到抱歉

最佳答案

要优先考虑 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.

关于mysql - 按多个条件排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700652/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com