簡體   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