如何在SQL查询中连接两个表而不重复

时间:2011-12-15 12:02:01

标签: sql sql-server-2008 tsql

User_Master (ID is Primary Key   identity)

ID      Name    Age      Gender
1       James   25       Male
2       John    30       Male

User_Image (User_Id is foreign key from User_Master)

ID     User_Id   Thumbnail
1         2       ABC.Jpeg
2         2       AB.jpeg

我需要从User_Master获取所有字段,并从User_Image

获取所选用户的一个缩略图名称

像这样:

User_Id    Name         Age      Gender Thumbnail
1          James        25       Male   null
2          John         30       Male   ABC.Jpeg

1 个答案:

答案 0 :(得分:3)

一种方法,假设你想要具有最低id的图像,因为显然有多个选项;

select 
    id, name, age, gender, thumbnail 
from (
    select
        rank() over (partition by m.id order by i.id asc) as rank,
        m.id,
        name, 
        age, 
        gender, 
        thumbnail
    from
        User_Master m left join User_Image i on (i.user_id = m.id)
) t where rank = 1