簡體   English   中英

根據另一列的最大值從表中選擇列

[英]Selecting columns from tables based on max value of another column

我有兩個表,我想要來自first_table的列輸入和來自second_table的列 output 基於最新完成時間

第一表:

id    input    
--------------
1     America    
2     China      
3     Russia     
2     China      
3     Russia     

second_table

id    output     finished_time
-------------------------------------------------
1     Washington    10/5/2019 10:05:13 PM +00:00
2     Shanghai      10/6/2019 10:05:13 PM +00:00
3     Kazan         10/7/2019 10:05:13 PM +00:00
2     Beijing       10/10/2019 10:05:13 PM +00:00
3     Moscow        10/11/2019 10:05:13 PM +00:00

結果表

id    input      output  
-----------------------------
1     America    Washington
2     China      Beijing
3     Russia     Moscow

我正在嘗試使用此查詢:

SELECT input, second_table.output
FROM first_table
INNER JOIN second_table ON first_table.id = second_table.id 
                        AND Max(finished_time)

您可以在連接的on子句中使用相關子查詢:

select
    f.*,
    s.output
from first_table f
inner join second_table s
    on  s.id = f.id
    and s.finished_time = (
        select max(s1.finished_time)
        from second_table s1
        where s1.id = s.id
    )

對於此處的性能,您需要在second_table(id, finished_time)上建立索引。

這也可以用not exists的條件來表示:

select
    f.*,
    s.output
from first_table f
inner join second_table s 
    on  s.id = f.id
    and not exists (
        select 1 
        from second_table s1
        where s1.id = s.id
        and s1.finished_time > s.finished_time

    )

最后,另一種選擇是使用 window function 進行排名

select id, input, output
from (
    select
        f.*,
        s.output,
        rank() over(partition by s.id order by s.finished_time desc) rn
    from first_table f
    inner join second_table s on s.id = f.id
) x
where rn = 1

您可以嘗試解決方案並選擇您更好理解或執行速度更快的解決方案。

您可以使用每個國家/地區的最大finished_time時間的派生表,然后將其加入國家和城市表:

SELECT t1.id, t1."input", t2."output"
FROM (SELECT DISTINCT id, "input"
      FROM first_table) t1
JOIN second_table t2 ON t2.id = t1.id
JOIN (SELECT id, MAX(finished_time) AS max_time
      FROM second_table t2
      GROUP BY id) m ON m.id = t2.id AND m.max_time = t2.finished_time
ORDER BY t1.id

Output:

ID  input       output
1   America     Washington
2   China       Shanghai
3   Russia      Kazan

dbfiddle 上的演示

請注意,我已將SELECT DISTINCT添加到first_table ,因為您在該表中有重復的行,這將導致 output 中的行重復。

如果您的 second_table.finished_time 有關聯的索引,這也很有效

SELECT input , second_table.output
FROM first_table
INNER JOIN second_table ON first_table.id= second_table.id
ORDER BY second_table.finished_time DESC
limit 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM