[英]Mysql Select query with limit
我有美國郵政編碼的 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
如果您運行的是 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.