SQL 查询每个给定位置的供应商数量最多

SQL query to find the most number of vendors per a given location

你能帮我找到正确的 MySQL 查询以获得每个给定位置的最多供应商并按名称和商店名称列出所有供应商吗:

1 - 查询必须找出供应商数量最多的位置,然后按名称列出供应商和他们工作的商店名称。

我有以下表格:

CITIES 
(
 ID "unique",
 NAME
)


SHOPS
(
 ID "unique",
 NAME,
 CITY_ID ( foreign key of CITIES TABLE ID)
)

VENDORS
(
 ID "unique",
 NAME,
 SHOP_ID ( foreign key of SHOPS TABLE ID)
)

带有虚拟数据的示例

CITIES : NY, SF

SHOPS: Boom - NY, Flash - NY, Sofast - SF

Vendors:

Mark : Boom,
John : Boom,
Carlos : Sofast,
Alex : Sofast,
David : Flash,
James: Flash

纽约的供应商数量最多,因此应该列出

Mark : Boom, John : Boom, David : Flash, James: Flash

如果您是 运行 MySQL 8.0,您可以使用 window 函数来解决此问题:

select *
from (
    select x.*, rank() over(order by cnt) rn
    from (
        select v.*, count(*) over(partition by c.id) cnt
        from cities c
        inner join shops   s on s.city_id = c.id
        inner join vendors v on v.shop_id = s.id
    ) t
) t
where rn = 1

最内层查询连接三张表,统计每个城市有多少商贩。下一级按计数降序排列记录。最后,最后一级过滤 top-ranked 行。

检查这是否有效 -

Select vendors.name, shops.name 
from 
cities inner join shops on cities.id= shops.city_id
inner join vendors on shops.id = vendors.shop_id
where cities.id = (select id from (select cities.id, count(1) from 
cities inner join shops on cities.id= shops.city_id 
inner join vendors on shops.id = vendors.shop_id 
group by cities.id order by 2 desc) limit 1)