1

I couldn't figure out how to join these two tables and get the result with NULL value that I want. I played around with LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN..., but couldn't get it to work. Please see this below.

Table1:

NameID  Name
1       N1
2       N2
3       N3
4       N4
5       N5

Table2:

NameID  AnotherID   Value
1       AID-111     1000
2       AID-222     2000
2       AID-222     3000
3       AID-333     4000
4       AID-444     5000


Select ...
JOIN Table1 and Table2
WHERE AnotherID = 'AID-222' 

This is the result I want:

NameID  Name    AnotherID   VALUE
1       N1      NULL        NULL
2       N2      AID-222     2000
3       N3      AID-222     3000    
4       N4      NULL        NULL    
5       N5      NULL        NULL

Please help. Thanks!

4

2 回答 2

4

您没有解释为什么要返回值2000而不是,3000但您可以使用LEFT JOIN 带有子查询的 a 来获取结果:

select t1.nameid,
  t1.name,
  t2.anotherid,
  t2.value
from table1 t1
left join
(
  select nameid, anotherid, min(value) value
  from table2
  where anotherid = 'AID-222'
  group by nameid, anotherid
) t2
  on t1.nameid = t2.nameid;

请参阅SQL Fiddle with Demo。这给出了结果:

| NAMEID | NAME | ANOTHERID |  VALUE |
--------------------------------------
|      1 |   N1 |    (null) | (null) |
|      2 |   N2 |   AID-222 |   2000 |
|      3 |   N3 |    (null) | (null) |
|      4 |   N4 |    (null) | (null) |
|      5 |   N5 |    (null) | (null) |
于 2013-04-17T23:18:39.350 回答
0

我们也可以使用全连接,它也会给你答案:

tableA从t1中选择 t1.nameid,t1.name,t2.anotherid,t2.value

full outer join
(
    select nameid,anotherid,value from tableB 
    where anotherid IN ('AID-222','AID-333') 

) t2 
on t1.nameid = t2.nameid;
于 2018-12-19T05:10:00.090 回答