我有下表:
ID Category_ID Score Name
1 1 60 Name_1
2 1 50 Name_2
3 2 40 Name_3
4 3 30 Name_4
5 4 10 Name_5
假设我运行以下查询:
SELECT * from table ORDER BY Score DESC LIMIT 0, 2
这将带给我:
ID Category_ID Score Name
1 1 60 Name_1
2 1 50 Name_2
如何避免在我的结果中重复使用Category_ID(尽可能多),但将ORDER BY得分作为第一个条件。例如,我如何才能获得以下内容:
ID Category_ID Score Name
1 1 60 Name_1
3 2 40 Name_3 <-- Following higher score with different Category_ID
和
SELECT * from table ORDER BY Score DESC LIMIT 1, 2
预期结果为:
ID Category_ID Score Name
2 1 50 Name_2
4 3 30 Name_4
SELECT * from table ORDER BY Score DESC LIMIT 2, 2
预期的结果是:
ID Category_ID Score Name
5 4 10 Name_5
谢谢!
答案 0 :(得分:0)
您只需要选择所需的ID。这将需要连接回原始表。此版本提供最小ID的结果:
select t.*
from t join
(select category_id, min(id) as minid
from t
group by category_id
) tsum
on t.id = tsum.minid
order by max_score
limit 0, 2
如果您想获得最高分,请改为:
select t.*
from t join
(select category_id, max(score) as maxscore
from t
group by category_id
) tsum
on t.category_id = tsum.category_id and
t.score = tsum.maxscore
order by max_score
limit 0, 2
当然,这假设最高分只出现在一条记录上。