在JOIN上从SQL第二个表中获取最新结果

table_a

ID        Status      NAME
---------------------------------    
1        pending      RAM
2        pending      SHYAM
3        pending      JULIEN
4        pending      KRISH 
5        pending      Jenkins
6        accepted     K8s 

table_b

ID       Values        Datetime     TYPE
---------------------------------------------    
1        L1          2018-06-02      L
1        L2          2019-07-20      L
1        G1          2019-09-20      G
2        L1          2019-09-20      L
2        K1          2019-09-15      K
3        M1          2019-10-22      M
4        R1          2019-10-23      R

预期结果:

NAME     values
--------------   
RAM       L2
SHYAM     L1
JULIEN    ""
KRISH     ""
Jenkins   ""
K8s       ""

查询:我在下面的查询中进行了尝试,但对我而言无效。

SELECT a.NAME,b.values 
FROM table_a a 
   LEFT JOIN table_b b ON a.ID=b.ID 
where a.Status ='pending' 
  and b.type='L';
hongchengge 回答:在JOIN上从SQL第二个表中获取最新结果

有两个问题:

  1. 为了从table_a获取所有行,您将需要将where条件移至join子句。
  2. 您可以在postgres中使用DISTINCT ON来获取每个用户的最新条目:
select DISTINCT ON (name)
a.name,b.values
FROM table_a a
LEFT JOIN table_b b ON a.id = b.id AND b.type = 'L' and a.status = 'pending'
ORDER BY name,datetime desc;

,

您可以使用相关子查询进行过滤:

select a.name,b.values
from table_a a
inner join table_b b
    on  a.id = b.id
    and b.type='L'
    and b.datetime = (
        select max(b1.datetime)
        from table_b b1
        where b1.id = b.id
    )
where a.status ='pending' 
本文链接:https://www.f2er.com/3165320.html

大家都在问