左连接链接到多行只返回一个

时间:2009-12-14 20:36:12

标签: join outer-join

我正在尝试加入两个表(称为table1和table2),但每个匹配只返回1个条目。在表2中,有一个名为“current”的列,它是'y','n'或'null'。我已经离开了加入两个表并放置了一个where子句来获取'y'和'null'实例,这些很容易。我需要帮助来获取连接到只有'n'的行的行,以返回'none'或'null'的一个实例。这是一个例子

表1 ID
1
2
3

表2
ID | table1ID |当前
1 | 1 | ÿ
2 | 2 |空
3 | 3 | ñ
4 | 3 | ñ
5 | 3 | n

我当前的查询加入table1.ID = table2.table1ID然后有一个where子句(其中table2.current ='y'或table2.current ='null')但是当没有'时它不起作用y'和值不是'null'。

有人可以提出一个像我一样加入表格的查询,但是像这样从table1获取所有3条记录吗?

查询返回

ID | table2ID |当前
1 | 1 | ÿ
2 | null |空
3 | 3 | null或none

3 个答案:

答案 0 :(得分:1)

首先,我假设“null”值实际上是字符串而不是DB值NULL。 如果是这样,下面的查询应该有效(注意INS子ON子句中的where条件的包含)

select 
table1.ID as ID
,table2.ID as table2ID
,table2.current 
from table1 left outer join table2 
on (table2.table1ID = table1.ID and 
(table2.current in ('y','null'))

如果这确实有效,我强烈建议将“null”字符串值更改为其他内容,因为它完全是误导性的...您或其他开发人员将来会浪费时间调试它。

如果“null”在实际上是指空值,则将上述查询更改为:

select 
table1.ID as ID
,table2.ID as table2ID
,table2.current 
from table1 left outer join table2 
on (table2.table1ID = table1.ID and 
(table2.current = 'y' or table2.current is null))

答案 1 :(得分:0)

你需要决定table2中三行中哪一行你想要table1id = 3:

3 | 3 | n
4 | 3 | n
5 | 3 | n

标准是什么?

答案 2 :(得分:0)

select t1.id
     , t2.id
     , case when t2.count_current > 0 then
           t2.count_current 
       else
           null
       end as current
from table1 t1
left outer join
(
  select id
  , max(table1id)
  , sum(case when current = 'y' then 1 else 0 end) as count_current
  from table2
  group by id
) t2
on t1.id = t2.table1id

尽管正如一些人所指出的那样,一旦你的表2中有多行'y',这可能无法正常工作。

相关问题