子查询左连接引用父 ID
Subquery left join refer to parent ID
我正在尝试查询以获取每个用户的最新汽车:
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 子句中好像写着 Unknown column "users.userid"
我试图删除 cars.userid=users.userid 部分,但它只会获取 1 辆最新的汽车,并将其贴在每个用户身上。
有什么方法可以实现我想要的吗?谢谢!!
也许有更好更有效的查询方式。这是我的解决方案;
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;
一个选项是使用子查询过滤 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)
上的索引。
请注意,如果您在 cars
中有重复的 (userid, year)
,那么每个用户可能 return 多辆汽车。最好有一个真实的日期而不是只有年份。
为此,我通常使用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;
我正在尝试查询以获取每个用户的最新汽车:
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 子句中好像写着 Unknown column "users.userid" 我试图删除 cars.userid=users.userid 部分,但它只会获取 1 辆最新的汽车,并将其贴在每个用户身上。
有什么方法可以实现我想要的吗?谢谢!!
也许有更好更有效的查询方式。这是我的解决方案;
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;
一个选项是使用子查询过滤 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)
上的索引。
请注意,如果您在 cars
中有重复的 (userid, year)
,那么每个用户可能 return 多辆汽车。最好有一个真实的日期而不是只有年份。
为此,我通常使用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;