复杂的条件加入

时间:2014-05-05 19:27:32

标签: mysql sql sql-server oracle11g

Table B
PropertyID  Property
40      (old)  Retirement 
40      (old)  Retirement 
40      (old)  Retirement 
40      (old)  Retirement 
40      (old)  Retirement 

Table A

ProplistID  ProplistCode    ProplistName    PropertyID  PropertyCode PropertyName
101 evergree    Evergreen   30  453 Retirement Center
101 evergree    Evergreen   31  454 Retirement Community
101 evergree    Evergreen   32  443 Retirement Center
101 evergree    Evergreen   33  444 Retirement Community

我的查询

SELECT  t1.*, t2.PropertyCode 
FROM    Test.dbo.Table A T1 
        INNER JOIN Test.dbo.Table T2 ON T1.PropertyID = T2.ProplistID;

UNION ALL 

SELECT t1.*, t2.PropertyCode
FROM   Test.dbo.TABLE A T1
       INNER JOIN Test.dbo.TABLE B T2 ON T1.PropertyID = T2.PropertyID; 

ORDER BY 1

您好我有这个复杂的加入,我正在努力。

我有两张桌子

**

  • 表1

**

Col A   Col B
1       3
2           11
3           1
4           11
5           3
6           3
7           11

**

  • 表2

**

表2

Col A   Col B   Col C   Col D
1   Hello   3   Bye
2   Hello   4   Bye
5   Hello   6   Bye
7   Hello   11  Bye
8   Hello   12  Bye
9   Hello   13  Bye
20  Hello   14  Bye

我需要加入它们以获得下面提到的表格

Col A   Col B   Col C
1   3   Hello
2   11  Hello
3   1   Bye
4   11  Bye
5   3   Hello
6   3   Bye
7   11  Hello

表1 Col A具有一些ID,其在col B中具有对应的值3或11

表格需要加入

如果(表1.Col A.Value = 3)

因此表3. Col C = Hello

然后加入(表1.Col A =表2. Col A)

其他(表1.Col A.Value = 3)

然后加入(表1.Col A =表2. Col C)

表3 Col C = Bye

请帮助我。

2 个答案:

答案 0 :(得分:0)

据我所知,我可以到达目前为止。试一试

select t1.cola,
t1.colb,
'Hello' as colc
from table1 t1
inner join
table2 t2
on t1.cola = t2.cola

union all

select t1.cola,
t1.colb,
'Bye' as colc
from table1 t1
inner join
table2 t2
on t1.cola = t2.colc 
order by t1.cola

在此处查看演示小提琴http://sqlfiddle.com/#!6/699ee/5

修改

你得到这样的结果原因;您加入T1.PropertyID = T2.PropertyID并且两个表的PropertyID中没有匹配的值。得到0行。执行左连接肯定会导致无法匹配键的原因。

希望这个解释对你有用。

最终编辑:

我通过更改您发布的实际数据(以便我们可以匹配)创建了一个示例小提琴并测试了您的查询。它工作得很好。请参阅此处的实际数据和表格架构http://sqlfiddle.com/#!6/ab954/3

答案 1 :(得分:0)

create table #t1 (ColA int,  ColB int)
insert #t1 values
(1,  3),
(2, 11),
(3,  1),
(4, 11),
(5,  3),
(6,  3),
(7, 11)

create table #t2 (ColA int,  ColB char(5), ColC int,  ColD char(3))
insert #t2 values
(1 ,  'Hello',   3 ,  'Bye'),
(2 ,  'Hello',   4 ,  'Bye'),
(5 ,  'Hello',   6 ,  'Bye'),
(7 ,  'Hello',   11,  'Bye'),
(8 ,  'Hello',   12,  'Bye'),
(9 ,  'Hello',   13,  'Bye'),
(20,  'Hello',   14,  'Bye')


select #t1.cola, #t1.colb, #t2.colb
from #t1
inner join #t2
on #t1.cola = #t2.cola 
union all
select #t1.cola, #t1.colb, #t2.cold
from #t1
inner join #t2
on #t1.cola = #t2.colc 
order by 1