2017-10-12 59 views
0

我正在写一个长查询来获取一些数据在一起。这是一个模拟数据:SQL复杂的连接,如果条件

表1:

a|b|c|d|e 
1|1|2|2|134 

表2:
A2,B2,C2,D2,E2是复合键

a2|b2|c2|d2|e2 |f2 |ax2|bx2|cx2|dx2|ex2 
1 |1 |2 |2 |134 |Orange|1 |1 |2 |2 |155 
1 |1 |2 |2 |155 |Apple |Null|Null|Null|Null|Null 

我的查询是这样的:

Select * from Table1 
inner join 
Table2 on Table1.a=Table2.a2 and Table1.b=Table2.b2 and Table1.c=Table2.c2 and Table1.d=Table2.d2 and Table1.e=Table2.e2 

这给了我

橙色

答案我需要的是

苹果

表2是相当弄乱了,还等什么,我要做的是让A,B ,c,d,e,然后将它插入到Table2中,得到ex2值,再次运行Table2以通过用ex2替换e2来获得Apple,同时使a2,b2,c2,d2保持不变。

就像我刚才提到的那样有点复杂,所以如果你需要的话请询问更多细节。我试图尽可能地给予。

我想这太(仍然没有喜悦):

Select y.a2,y.b2,y.c2,y.d2,(Select case when e2 is not null and ex2 is not null then ex2 else e2 end) from Table1 x inner join Table2 y on x.a=y.a2 and x.b=y.b2 and x.c=y.c2 and x.d=y.d2 and Table1.e=Table2.e2 
+1

你需要给真正的表结构和实际查询,或者它会很困难提供帮助。 – tommyO

+1

它应该让你橙色E2在表1和表2中都是134。为什么它应该给你155?哦,这是一个层次结构。层次总是只有1级?如果是的话,再次向table2添加一个连接,如果它可能是n级的,那么你需要一个递归cte或者用于xml路径来遍历层次结构。 – xQbert

+0

@xQbert在某些情况下,答案是Apple/Orange。如果你使用表2中的e2,表1会给你橙色。如果你想要苹果,那么你需要得到ex2的价值,然后插入e2来获得苹果。所以是的,这是一种层次结构。 – SQLserving

回答

2

只需要添加另外加入到查询的左联接遍历额外的一层,使用聚结,显示的最低水平(如果存在),或者如果没有,则是最低的。

SELECT Coalesce(C.F2, B.F2) as F2 
FROM Table1 A 
LEFT JOIN TABLE2 B 
    on A.a= b.a2 
and A.B = B.B2 
and A.C = B.C2 
and A.D = B.D2 
and A.E = B.E2 
LEFT JOIN TABLE3 C 
    on B.Ax2 = C.A2 
and B.Bx2 = C.B2 
and B.Cx2 = C.c2 
and B.Dx2 = C.D2 
and B.Ex2 = C.E2 
+0

这样做的工作! – SQLserving

1

这是临时表的一个例子。

DROP TABLE IF EXISTS #Table1; 
CREATE TABLE #Table1 (
    a int not null, 
    b int not null, 
    c int not null, 
    d int not null, 
    e int not null, 
); 
INSERT INTO #Table1 VALUES (1, 1, 2, 2, 134); 

DROP TABLE IF EXISTS #Table2; 
CREATE TABLE #Table2 (
    a2 int not null, 
    b2 int not null, 
    c2 int not null, 
    d2 int not null, 
    e2 int not null, 
    f2 nvarchar(10) not null, 
    ax2 int null, 
    bx2 int null, 
    cx2 int null, 
    dx2 int null, 
    ex2 int null, 
    CONSTRAINT PK_Table2 PRIMARY KEY (a2, b2, c2, d2, e2), 
); 
INSERT INTO #Table2 VALUES 
    (1, 1, 2, 2, 134, 'Orange', 1, 1, 2, 2, 155), 
    (1, 1, 2, 2, 155, 'Apple', null, null, null, null, null); 

SELECT Branch.a2 
    , Branch.b2 
    , Branch.c2 
    , Branch.d2 
    , Leaf.e2 
    , Leaf.f2 
FROM #Table1 AS Root 
INNER JOIN #Table2 AS Branch 
    ON Root.a = Branch.a2 
    AND Root.b = Branch.b2 
    AND Root.c = Branch.c2 
    AND Root.d = Branch.d2 
    AND Root.e = Branch.e2 
INNER JOIN #Table2 AS Leaf 
    ON Branch.ex2 = Leaf.e2; 

结果是

+---------------------+ 
|a2|b2|c2|d2|e2 |f2 | 
+---------------------+ 
| 1| 1| 2| 2|155|Apple| 
+---------------------+ 
+1

你的查询工作得很好,但是xQbert第一次。非常感激! – SQLserving

+0

左连接,而不是内部incase没有叶子?就像155上的情况一样? – xQbert

+0

当然,如果这是你的意图。这个问题有点难以分辨。 –