用于查找每个给定位置的最多供应商数量的 SQL 查询
Posted
技术标签:
【中文标题】用于查找每个给定位置的最多供应商数量的 SQL 查询【英文标题】:SQL query to find the most number of vendors per a given location 【发布时间】:2020-12-21 19:55:27 【问题描述】:您能帮我找到正确的 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
【问题讨论】:
欢迎来到 SO。请看:Why should I provide an MCRE for what seems to me to be a very simple SQL query? 【参考方案1】:检查这是否有效 -
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)
【讨论】:
【参考方案2】:如果您运行的是 MySQL 8.0,您可以使用窗口函数来解决这个问题:
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
最内部的查询连接三个表,并计算每个城市有多少供应商。下一级按降序排列记录。最后,最后一级过滤排名靠前的行。
【讨论】:
以上是关于用于查找每个给定位置的最多供应商数量的 SQL 查询的主要内容,如果未能解决你的问题,请参考以下文章