如何仅加入第一行,忽略更多匹配

How to Join only first row, disregard further matches

我有2张桌子

Table Users: 
UserID  |  Name

Table Cars: 
CarID | Car Name | FK_UserID

一个用户可以拥有多于一辆车。

我想加入每个用户只有 1 辆车,而不是更多。

看过这里的其他话题后, 我尝试了以下方法:

Select users.UserID, users.name, carid
from Users
join cars
on users.UserID = 
    (
    select top 1 UserID
    from users
    where UserID = CarID
    )

但每个用户仍然 returns 超过 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;
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 函数的一种方法。

另一种方法

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)

最好是做一个子查询并在其中使用 group-by 以 return 只有一个用户和每个用户一辆车。然后将其加入外部用户 table。

这是一个例子:

select *
from user_table u
    join   (
           select userid
                , max(carname)
           from cars
           group by userid

           ) x on x.userId = u.userId

或者如果您需要特定顺序,您可以使用上面的 row_number() 示例(这个示例或他们的示例都可以)