t-sql查询获取Table_A中的所有行,这些行在Table_B中至少有一个匹配的relatedid

时间:2010-08-27 22:06:45

标签: sql tsql sql-server-2008

基于下表

Table_A

Id  RelatedId
---------------
1   1
1   2
1   3
2   4
2   5
2   2
3   7
3   8
4   9

Table_B

RelatedId  Name
--------------
2          A
3          B

我想获取Table_A中的所有行,这些行在Table_B中至少有一个匹配的relatedid。来自Table_A的Ids在Table_B中没有匹配,在结果表中将有单行。

因此在这种情况下输出(结果表)将是

Id  RelatedId
---------------
1   1
1   2
1   3
2   4
2   5
2   2
3   Null
4   Null

编辑:似乎问题文本对许多人来说很困惑。所以详细说明:

Table_A Id 1在table_B中具有2和3(相关ID)匹配。因此输出将具有Table_A中的1的所有行。来自Table_A的类似Id 2在表_B中具有2个(相关Id)匹配。因此,将拾取与Table_A中的2对应的所有行。由于3在table_B中没有任何匹配的relatedid,因此它将在结果表中显示为NULL,作为relatedid。

3 个答案:

答案 0 :(得分:3)

with validids as (
 select distinct id 
 from Table_A 
  inner join Table_B on 
   Table_A.relatedid = Table_B.relatedid
)
select 
  id,
  relatedid
from Table_A 
where id in (select id from validids)
union 
select distinct
 id, 
 null
from Table_A
where id not in (select id from validids)

答案 1 :(得分:2)

尝试:

  Select Distinct Id, Related_Id
  From Table_A 
  Where Related_Id In 
      (Select Related_Id From Table_B) 

答案 2 :(得分:1)

这应该做你想要的:

with IdsWithMatchInB(Id) as (
  select distinct
    Id
  from Table_A
  where Table_A.RelatedId in (
    select Table_B.RelatedId
    from Table_B
  )
)
  select
    Table_A.Id,
    CASE WHEN IdsWithMatchInB.Id IS NULL
         THEN NULL
    ELSE Table_A.RelatedId END AS RelatedId
from Table_A
left outer join IdsWithMatchInB
on IdsWithMatchInB.Id = Table_A.Id

这是另一个通过将子查询放在CASE表达式中来避免DISTINCT的选项:

select
  Id,
  case when Id in (
    select Id
    from Table_A as Acopy
    where Acopy.RelatedId in (
      select
        RelatedId 
      from Table_B
    )
  )
  then RelatedId
  else null end as RelatedId
from Table_A;

对于您的特定数据和索引,其中一个可能更有效。