如何通过左连接获得唯一结果

时间:2015-12-02 05:33:04

标签: sql sql-server sql-server-2008 sql-server-2012

我有两张表1)Users和2)Images

Users table

id  name     
1   xyz  
2   abc


Images table

id  path    
1   ~/img/12.jpg
1   ~/img/34.jpg
2   ~/img/de.jpg
2   ~/img/rt.jpg

所以现在当我写查询时:

select id, name, path
from users
    left join images on images.id = users.id
where id =1

然后它会给我输出像:

id  name path
1   xyz  ~/img/12.jpg
1   xyz  ~/img/34.jpg

但我需要输出如:

   id   name   path1        path2
    1   xyz  ~/img/12.jpg  ~/img/34.jpg

我怎么能得到这个?

4 个答案:

答案 0 :(得分:1)

对于您的输出我们可以使用Cross Apply和Pivot

来实现
declare @users TABLE 
    (id   INT,      varchar(4))
;

INSERT INTO @users
    (id, name)
VALUES

    (1, 'xyz'),
    (2, 'abc')
;


declare @images  TABLE 
    (id int, path varchar(12))
;

INSERT INTO @images
    (id, path)
VALUES

    (1, '~/img/12.jpg'),
    (1, '~/img/34.jpg'),
    (2, '~/img/de.jpg'),
    (2, '~/img/rt.jpg')
;
select * from (
select s.id, 
s.name , 
images.path,
COL + CAST(row_number()over(PARTITION BY s.ID ORDER BY COL) AS VARCHAR) RN 
from @users s 
left join @images images  
on images.id=s.id
CROSS APPLY (VALUES ('path',path))CS(Col,val)
    where s.id =1)P
    PIVOT (MAX(PATH) FOR RN IN ([path1],[path2]))P 

答案 1 :(得分:1)

固定为2路时很容易

;WITH paths AS
(
   SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY path) AS Seq FROM Images
)
SELECT 
  *
  (SELECT path FROM paths WHERE id = u.id AND Seq = 1) Path1, 
  (SELECT path FROM paths WHERE id = u.id AND Seq = 2) Path2 
FROM Users u 
WHERE id = 1

答案 2 :(得分:0)

为最小和最大路径执行GROUP BY

select u.id, u.name, min(i.path), max(i.path)
from users u
    left join images i on i.id = u.id
group by u.id, u.name

只要用户只有一两条路径就可以正常工作。

答案 3 :(得分:-1)

您可以像

一样使用Group
select id, name , path from users left join images on images.id=users.id
where id =1 group by id