通过“选择”选择每个组的前两个记录的最佳方式是什么?命令? [英] What is the best way to select the first two records of each group by a "SELECT" command?
本文介绍了通过“选择”选择每个组的前两个记录的最佳方式是什么?命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有下表:
id组数据
1 1 aaa
2 1 aaa
3 2 aaa
4 2 aaa
5 2 aaa
6 3 aaa
7 3 aaa
8 3 aaa
通过SELECT命令选择每个组的前两个记录的最佳方法是什么?
如果没有好的方法可以这样做,那么你会建议哪些例程?(在PHP中)
(模型结果)
1 1 aaa
2 1 aaa
3 2 aaa
4 2 aaa
6 3 aaa
7 3 aaa
我知道通过a.id> = b.id进行交叉连接一个子查询可以工作,但我正在寻找一个更具可扩展性的解决方案,可以应用在具有数百万条记录的表上。谢谢
解决方案
select a。*
from Tablename a
其中
(
)从Tablename中选择count(*)
作为b
,其中a.group = b.group和a.id> = b.id
) < = 2
For instance I have the following table:
id group data
1 1 aaa
2 1 aaa
3 2 aaa
4 2 aaa
5 2 aaa
6 3 aaa
7 3 aaa
8 3 aaa
What is the best way to select the first two records of each group by a "SELECT" command? If there is no good way to do so, what routine do you suggest?(in PHP)
(model outcome)
1 1 aaa
2 1 aaa
3 2 aaa
4 2 aaa
6 3 aaa
7 3 aaa
I knew that cross-joining by a.id >= b.id in a sub-query can be working but I am looking for a more scalable solution that can be applied on a table with millions of records. Thanks
解决方案
select a.*
from Tablename a
where
(
select count(*)
from Tablename as b
where a.group = b.group and a.id >= b.id
) <= 2
这篇关于通过“选择”选择每个组的前两个记录的最佳方式是什么?命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文