【问题标题】:SQL get value based on corresponding min/max(value) from column in another related tableSQL 根据另一个相关表中的列中相应的 min/max(value) 获取值
【发布时间】:2020-09-26 08:46:19
【问题描述】:

我有以下两个由 ID 列关联的表作为主键。我的目标是从表 1 中的“名称”列中查询与表 2 中的最大和最小“分数”列值对应的 User_id 的值。

Table 1:

| ID | Name |
|----|------|
| 1  | Foo  |
| 2  | Bar  |
| 3  | Zoo  |
| 4  | Bar  |
| 5  | Foo  |
| 6  | Zar  |

Table 2:

| ID | Score |
|----|-------|
| 1  | 98    |
| 2  | 67    |
| 3  | 86    |
| 4  | 59    |
| 5  | 75    |
| 6  | 73    |

最终的输出应该是这样的:

| Name | Score |
|------|-------|
| Foo  | 98    |
| Bar  | 59    |

【问题讨论】:

    标签: mysql sql join


    【解决方案1】:

    你可以试试下面的-

        select name, score 
        from table1 t1 join table2 t2 on t1.id=t2.id
        where 
        score=(select max(score) from t2)
        or 
        score=(select min(score) from t2)
    

    【讨论】:

      【解决方案2】:
      (
      SELECT name, score
      FROM table1 NATURAL JOIN table2
      ORDER BY 2 ASC LIMIT 1
      )
      UNION ALL
      (
      SELECT name, score
      FROM table1 NATURAL JOIN table2
      ORDER BY 2 DESC LIMIT 1
      )
      

      【讨论】:

      • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
      【解决方案3】:

      如果你运行的是 MySQL 8.0,你可以使用窗口函数:

      select t1.name, t2.score
      from table1 t1
      inner join (
          select t2.*, 
              rank() over(order by score) rn_asc, 
              rank() over(order by score desc) rn_desc
          from table2 t2
      ) t2 on t2.id = t1.id
      where 1 in (rn_asc, rn_desc)
      

      这个想法是通过增加和减少score 对table2 的记录进行排名,并使用该信息进行过滤。请注意,这允许顶部和底部的联系。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-06
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多