繁体   English   中英

SQL根据来自另一个相关表中的列的相应最小值/最大值(值)获取值

[英]SQL get value based on corresponding min/max(value) from column in another related table

我有以下两个由 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    |

你可以试试下面的——

    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)
(
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
)

如果您运行的是 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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM