【问题标题】:Mysql how to combine having() with min()Mysql如何将have()与min()结合起来
【发布时间】:2020-05-15 21:14:17
【问题描述】:

我需要从按距离按 store_id 顺序分组的分支表中选择所有分支

换句话说,我需要找到每个商店最近的分店

select distinct  `branch_id`, `store_id`, `branch_name`,  distance 
from `store_branches` 
groupBy store_id having MIN(distance) 
orderBy `distance` asc

MIN(distance) 使查询返回空结果

我使用了因为 orderBy 没有做这项工作,因为 groupBy 在 orderBy 之前应用了

【问题讨论】:

  • 拥有MIN() 是什么?
  • MIN 距离:距离的最小值
  • HAVING 表示与您期望的不同。这是像WHERE 这样的条件。您要求的是具有非零最小值的东西,但您不在乎什么。

标签: mysql


【解决方案1】:

使用相关子查询:

select sb.`branch_id`, sb.`store_id`, sb.`branch_name`, sb.distance 
from `store_branches` sb
where sb.`distance` = (select min(distance) from `store_branches` where `store_id` = sb.`store_id`)

NOT EXISTS:

select sb.`branch_id`, sb.`store_id`, sb.`branch_name`, sb.distance 
from `store_branches` sb
where not exists (
  select 1 from `store_branches`
  where `store_id` = sb.`store_id` and `distance` < sb.`distance`
)

对于 MySql 8.0,您可以使用 RANK() 窗口函数:

select sb.`branch_id`, sb.`store_id`, sb.`branch_name`, sb.distance 
from (
  select *, rank() over (partition by `store_id` order by `distance`) rnk
  from `store_branches`
) sb
where sb.rnk = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 2012-03-17
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    相关资源
    最近更新 更多