SQL左连接问题

时间:2013-08-16 13:50:07

标签: sql sql-server-2008

表1

Id           value
1               1
1               4

表2

id      Detailid          value
 1       1                 1
 1       2                 2
 1       3                 3
 1       4                 4
 1       5                 5
 1       6                 6

我想要结果

Id      Detaild      value
1        1           1
1        2          null
1        3          null 
1        4          4
1        5          null
1        6          null

我的下面的查询为我提供了2个额外的行

select distinct t1.id,t2.detailid  
 ,case when t1.value IN(t2.Value) then t1.value else null end as value  
from table1 t1  
left outer join table2 t2  
on t1.id= t2.id 

我正在

Id       Detaild    value  
1        1          null ----dont need  
1        1          1  
1        2          null  
1        3          null   
1        4          null ---dont need  
1        4          4  
1        5          null  
1        6          null  

5 个答案:

答案 0 :(得分:1)

那是因为Table1中的一行没有DetailId 2和3的外键,那么它还能如何返回连接中的那些呢?

答案 1 :(得分:1)

SELECT t1.Id, t2.DetailId, t1.value 
FROM table1 AS t1 
LEFT OUTER JOIN table2 AS t2. ON t1.DetailId = t2.detailId 
WHERE t2.DetailId NOT IN (5,6);

答案 2 :(得分:0)

SELECT t1.Id, t1.DetailId, t1.value 
FROM table1 AS t1 
LEFT JOIN table2 AS t2. ON t1.Detaild = t2.detailid;

使用上述查询。

答案 3 :(得分:0)

根据您提供的数据,此查询将起到作用:

SELECT isnull(t1.Id,1), t2.Detailid, t1.value 
FROM Table2 AS t2
LEFT OUTER JOIN Table1 AS t1 ON t1.Detailid = t2.Detailid AND t1.ID = 1

SQLFIDDLE:http://www.sqlfiddle.com/#!3/4c808/8/0

编辑:

因此,根据您上次编辑,查看以下查询:

SELECT t2.Id, t2.Detailid, t1.value 
FROM Table2 AS t2
LEFT OUTER JOIN Table1 AS t1 ON t1.Id = t2.Id AND t1.value = t2.value
WHERE t2.Id = 1

SQLFIDDLE:http://www.sqlfiddle.com/#!3/94f21a/5/0

重新编辑:

SELECT t2.Id, t2.Detailid, t1.value 
FROM Table2 AS t2
LEFT OUTER JOIN Table1 AS t1 ON t1.Id = t2.Id AND t1.value = t2.value
WHERE t2.id IN (SELECT Id FROM Table1)

SQLFIDDLE:http://www.sqlfiddle.com/#!3/beede/7/0

如果(SELECT Id FROM Table1)返回太多行,请尝试使用以下内容:

 SELECT DISTINCT t2.Id, t2.Detailid, t1.value 
 FROM Table2 AS t2
 INNER JOIN Table1 AS t ON t.Id = t2.Id
 LEFT OUTER JOIN Table1 AS t1 ON t1.Id = t2.Id AND t1.value = t2.value

SQLFIDDLE:http://www.sqlfiddle.com/#!3/beede/9/0

答案 4 :(得分:0)

select t2.[Id],t2.Detailid,t1.value
from Table2 t2
left join Table1 t1
on t2.value = t1.value;

<强> FIDDLE