【问题标题】:Mysql MIN() Max() function with JOIN and GROUP BYMysql MIN() Max() 函数与 JOIN 和 GROUP BY
【发布时间】:2017-12-07 11:36:55
【问题描述】:

我有一个问题,我需要用 JOIN 和 GROUP BY 用 Mysql 找到 MIN() 和 MAX()。

我有 3 张桌子:

  • 父母(parent_id)
  • 孩子(child_id, parent_id)
  • 价格(price_id, child_id, price)

一个父母可以有多个孩子,一个孩子只有一个价格。

这是我获取父母所有价格的查询:

select   child.parent_id ,  price.child_id  , price.price
from parent 
 inner join  child on child.parent_id = parent.id 
 inner join price on price.child_id = child.id

我想找到父母的最低价格。但我不只想要价格,我想要 price_id !

你能帮我做这个查询来找到每个父母的 min() 价格的 price_id 吗?

这里是数据样本:

parent1 : parent_id=1
parent2 : parent_id=2

child1 : child_id=1 , parent_id=1
child2 : child_id=2 , parent_id=1
child3 : child_id=3 , parent_id=1

child4 : child_id=4 , parent_id=2
child5 : child_id=5 , parent_id=2
child6 : child_id=6 , parent_id=2

price1 : price_id=1 , child_id=1, price=15
price2 : price_id=2 , child_id=2, price=5
price3 : price_id=3 , child_id=3, price=10

price4 : price_id=4 , child_id=4, price=10
price5 : price_id=5 , child_id=5, price=20
price6 : price_id=6 , child_id=6, price=30

我想为 parent1 找到他孩子的最低价格的 id,结果是:price_id=2

我想为 parent2 找到他孩子的最低价格的 id,结果是:price_id=4

我想为 parent1 找到他孩子的 MAX price 的 id,结果是:price_id=1

我想为 parent2 找到他孩子的 MAX 价格的 id,结果是:price_id=6

谢谢!

【问题讨论】:

  • 更新您的问题并添加适当的数据样本和预期结果
  • .. 我没有看到数据样本..
  • 我用数据样本编辑了 ma 问题

标签: mysql join group-by


【解决方案1】:

您需要在选定的表上进行一些 cinner join

  select distinct  t.parent_id, price.price_id
  from price 
  inner join child on price.child_id = child.child_id
  inner join (
      select   
      parent.parent_id
      min(price) min_price
    from parent 
    inner join child on parent.parent_id = child.parent_id
    inner join price on price.child_id = child.child_id
    group by parent.parent_id ) t on t.min_price = price.price 
            and t.parent_id = child.parent_id

并查看您的结果

然后按结果分组

    select parent_id, min(price_id), price from ( 
    select distinct  t.parent_id, price.price_id, price.price
      from price 
      inner join child on price.child_id = child.child_id
      inner join (
          select   
          parent.parent_id
          min(price) min_price
        from parent 
        inner join child on parent.parent_id = child.parent_id
        inner join price on price.child_id = child.child_id
        group by parent.parent_id ) t on t.min_price = price.price 
                and t.parent_id = child.parent_id

    ) t 
    group by arent_id, price

【讨论】:

  • 如果父母有很多孩子的最低价格相同,您的查询不会只返回一个价格:(即使有很多最低价格相同的价格,我也只需要一个结果。
  • 对不起,它不起作用,它检索所有具有相同价格的 price_id ,而不仅仅是一个 :(
  • 显示结果样本.yiu have .. .我无法理解..没有适当的样本..
  • parent_id price_id price 831 5462 999 831 5471 999 831 5474 999 831 5479 999 831 5488 999 我只想要第一行。我只想要我所有父母的最低价格 ID,如果有很多相同的最低价格,我首先想要,例如,限制为 1,但放在哪里?
  • 你应该更新你的问题并添加示例..在评论中数据不清楚
猜你喜欢
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多