子查询左连接引用父id

bfnvny8b  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(349)

我正在尝试查询以获取每个用户的最新汽车:

select * from users 
    left join 
       (select cars.* from cars 
        where cars.userid=users.userid 
        order by cars.year desc limit 1) as cars
    on cars.userid=users.userid

它看起来像是在where子句中显示未知列“users.userid”,我试图删除cars.userid=users.userid部分,但它只获取1辆最新的汽车,并将其粘贴到每个用户。
有什么办法可以实现我的目标吗?谢谢!!

jpfvwuh4

jpfvwuh41#

一种选择是过滤 left join 使用子查询:

select * -- better enumerate the columns here
from users u
left join cars c 
    on  c.userid = u.userid
    and c.year = (select max(c1.year) from cars c1 where c1.userid = c.userid)

对于性能,请考虑 car(userid, year) .
请注意,如果您有重复的,这可能会为每个用户返回多辆车 (userid, year)cars . 最好有一个真正的约会,而不仅仅是一年。

pu3pd22g

pu3pd22g2#

为此,我通常使用 row_number() :

select *
from users u left join
     (select c.* , row_number() over (partition by c.userid order by c.year desc) as seqnum
      from cars c
     ) c 
     on c.userid = u.userid and c.seqnum = 1;
jpfvwuh4

jpfvwuh43#

也许有更好更有效的方法来查询这个。这是我的解决办法;

select users.userid, cars.*
from users
         left join cars on cars.userid = users.userid
         join (SELECT userid, MAX(year) AS maxDate
               FROM cars
               GROUP BY userid) as sub on cars.year = sub.maxDate;

相关问题