简体   繁体   English

Mysql Select 有限制的查询

[英]Mysql Select query with limit

I have MySQL table for US zip codes like我有美国邮政编码的 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 

..... .....

I want to use single select MySQL query to fetch only 2 cities for every states so final result look like below table我想使用单选 MySQL 查询为每个州仅获取 2 个城市,因此最终结果如下表所示

id     | zip_code  | city       |  State
1      |   99553   | Akutan     |  Alaska
2      |   99571   | Cold Bay   |  Alaska
4      |   36006   | Billingsley|  Alabama 
5      |   36008   | Booth      |  Alabama

If you are running MySQL 8.0, you can use row_number() :如果您运行的是 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

In earlier versions, you could use a correlated subquery for filtering:在早期版本中,您可以使用相关子查询进行过滤:

select t.*
from mytable t
where (
    select count(*) 
    from mytable t1 
    where t1.state = t.state and t1.zip_code <= t.zip_code
) <= 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM