限制一列中具有相同记录的行数?

Limit the number of rows with same record in one column?

我有一长串人名。姓史密斯的有数百人,姓金的有数百人等

如何select table 中的所有人,但最多只允许 6 个人同姓?

最简单的方法大概是使用变量:

select ll.*
from (select ll.*,
             (@rn := if(@ln = lastname, @rn + 1,
                        if(@ln := lastname, 1, 1)
                       )
             ) as rn
      from longlist ll cross join
           (select @ln := '', @rn := 0) params
      order by lastname
     ) ll
where rn <= 6;

有很多方法可以做你想做的事,其中一些非常复杂。任何确定性方法都会 rank the rows。您的任务是将 table 加入自身,并确定是什么让一个 "Smith" 小于另一个。

对名称进行排名后,您可以将它们再次加入 table(或使用 where exists)和 where rank < 7 或其他。