我有2张桌子
Table Users:
UserID | Name
Table Cars:
CarID | Car Name | FK_UserID
用户可以拥有超过1辆汽车。
我想加入每个只有1辆车的用户,而不是更多。
看过这里的其他线程, 我尝试了以下内容:
Select users.UserID, users.name, carid
from Users
join cars
on users.UserID =
(
select top 1 UserID
from users
where UserID = CarID
)
但是每个用户仍然会返回超过1个匹配。
我做错了什么?
答案 0 :(得分:1)
您可以使用ROW_NUMBER()
功能
select userid, username, carname
from
(
Select users.UserID as userid,
users.name as username,
cars.carname as carname,
ROW_NUMBER() OVER(PARTITION BY users.UserID ORDER BY users.UserID) AS r
from Users
join cars
on users.UserID = cars.FK_UserID
) XXX
where r = 1;
答案 1 :(得分:0)
with x as
(select row_number() over(partition by userid order by carid) as rn,
* from cars)
select u.userid, x.carid, x.carname
from users u join x on x.userid = u.userid
where x.rn = 1;
这是使用row_number
函数执行此操作的一种方法。
答案 2 :(得分:0)
另一种方法
select u.UserID,
u.name,
(select TOP 1 carid
from cars c
where u.UserID = c.FK_UserID
order by carid) carid -- Could be ordered by anything
from Users u
-- where only required if you only want users with cars
where exists (select * from car c where u.UserID = c.FK_UserID)
答案 3 :(得分:0)
最好是做一个子查询并使用group-by
来为每个用户只返回1个用户和一辆汽车。然后将其加入外部用户表。
以下是一个例子:
select *
from user_table u
join (
select userid
, max(carname)
from cars
group by userid
) x on x.userId = u.userId
或者你可以使用上面的row_number()
例子,如果你想要一个特定的订单(无论是这个例子还是他们的诀窍)