如果有人想尝试这个,就做了一个测试sqlfiddle...
http://sqlfiddle.com/#!9/904e18/2/0
在我的数据库中我有这个:
Group: A
Name: A-1, Points: 7pts
Name: A-2, Points: 6pts
Name: A-3, Points: 6pts
Name: A-4, Points: 5pts
Group: B
Name: B-1, Points: 1pts
Name: B-2, Points: 5pts
Name: B-3, Points: 4pts
Name: B-4, Points: 6pts
Group: C
Name: C-1, Points: 6pts
Name: C-2, Points: 8pts
Name: C-3, Points: 9pts
Name: C-4, Points: 2pts
我需要首先按照得分最高的总体领先者对其进行排序。 (C-3)
然后我需要按第二总体领先者排序,但不在总体领先者组中排序。 (A-1)
接下来,我需要按第三总领导者排序,但不在总领导者或第二领导者的组中(B-4)
然后按点数对其余部分进行排序。
所以它应该是这样的:
C-3
A-1
B-4
^^各组的领导者,按从高到低排序
-----
然后剩下的按分数从高到低排列,没有群体特异性。
最佳答案
您可以通过以下查询以您想要的方式获取前 3 名球队:
select * from teams
where points = (select max(points) from teams as t where t.`group` = teams.`group`)
order by points desc
您还可以通过以下查询以您想要的方式获取其余团队:
select * from teams
where name not in
(select name from teams
where points = (select max(points) from teams as t where t.`group` = teams.`group`))
order by points desc
问题是,如果您合并这两个查询,那么您将丢失它们包含的任何顺序。因此,为了合并这 2 个结果,您必须在 2 个结果中添加 sortKey 并在最终结果的排序中使用它,以便保留订购。查询如下:
(select *, 1 as SortKey from teams
where points = (select max(points) from teams as t where t.`group` = teams.`group`))
UNION ALL
(select *, 2 as SortKey from teams
where name not in
(select name from teams
where points = (select max(points) from teams as t where t.`group` = teams.`group`)))
order by SortKey, points desc
你也可以在这个sqlfiddle中看到它
关于MySQL多重排序并忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31849934/