MySQL选择查询有限制

我有适用于美国邮政编码的mysql表

id     | zip_code  | city       |  State
1      |   99553   | Akutan     |  Alaska
2      |   99571   | Cold Bay   |  Alaska
3      |   99583   | False Pass |  Alaska 
4      |   36006   | Billingsley|  Alabama 
5      |   36008   | Booth      |  Alabama
6      |   36051   | Marbury    |  Alabama 

.....

我想使用单个选择MySQL查询来为每个州仅获取2个城市 因此最终结果如下表所示

id     | zip_code  | city       |  State
1      |   99553   | Akutan     |  Alaska
2      |   99571   | Cold Bay   |  Alaska
4      |   36006   | Billingsley|  Alabama 
5      |   36008   | Booth      |  Alabama
h975969910 回答:MySQL选择查询有限制

如果您正在运行MySQL 8.0,则可以使用row_number()

select id,zip_code,city,state
from (
    select t.*,row_number() over(partition by state order by zip_code) rn
    from mytable t
) t
where rn <= 2

在早期版本中,您可以使用相关子查询进行过滤:

select t.*
from mytable t
where (
    select count(*) 
    from mytable t1 
    where t1.state = t.state and t1.zip_code <= t.zip_code
) <= 2
本文链接:https://www.f2er.com/2900492.html

大家都在问