Join 左键将链接连接到多行,只返回一行

Join 左键将链接连接到多行,只返回一行,join,outer-join,Join,Outer Join,我试图连接两个表(称为table1和table2),但每个匹配只返回一个条目。在表2中,有一个名为“current”的列,它是“y”、“n”或“null”。我左键连接了两个表,并放置了一个where子句来获取'y'和'null'实例,这些都很简单。我需要帮助才能使连接到只有“n”的行的行返回一个“none”或“null”实例。这里有一个例子 表1 ID 1 2 三, 表2 ID |表1ID |当前 1 | 1 | y 2 | 2 |空 3|3|n 4|3|n 5 | 3 | n 我当前的查询在t

我试图连接两个表(称为table1和table2),但每个匹配只返回一个条目。在表2中,有一个名为“current”的列,它是“y”、“n”或“null”。我左键连接了两个表,并放置了一个where子句来获取'y'和'null'实例,这些都很简单。我需要帮助才能使连接到只有“n”的行的行返回一个“none”或“null”实例。这里有一个例子

表1 ID
1
2
三,

表2
ID |表1ID |当前
1 | 1 | y
2 | 2 |空
3|3|n
4|3|n
5 | 3 | n

我当前的查询在table1.ID=table2.table1ID上联接,然后有一个where子句(其中table2.current='y'或table2.current='null'),但当没有'y'且值不是'null'时,这不起作用

有人能提出一个查询,像我这样加入表,但像这样从表1中得到所有3条记录吗

查询返回

ID |表2ID |当前
1 | 1 | y
2 |空|空

3 | 3 | null或none

您需要决定表2中表1id=3的三行中的哪一行:

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

标准是什么?

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

如果这确实有效,我强烈建议将“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))

尽管,正如Justsomeone所指出的,一旦表2中有多行带有“y”的数据,这可能不会像您预期的那样起作用。

我实际上不想要任何一行,我只需要知道没有“y”或null值,是的,这是DB null值,而不是字符串值。我需要试试这个,我所说的空值是我离开join时返回的值,而Table2中没有特定的行。这不会为table1 ID 3返回值,因为它没有“y”或不为空
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))
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