如果表值等于另一个,则在SQL中连接表

时间:2016-08-10 14:13:32

标签: sql access

我有3张桌子。它们都代表了一个过程的不同阶段。

表1:

ID   Process1

1    a       
2    b
3    c
4    d

表2:

ID   ID2     Process2
1    50        e
2    51        f
4    52        g 

表3:

IDfromPrevious   ID3   Process3
50               500   h
51               501   i
52               502   j
3                503   k

我想创建表4:

ID3  Process1  Process2  Process3
500   a          e           h
501   b          f           i
502   d          g           j
503   c                      k

问题是某个项目从进程1移动到3.其他项目从进程1移动到2到3.然而,所有内容都会在进程3处结束。该项目还会通过每个进程分配一个新ID。我在ms access 2016工作。

我不知道从哪里开始使用SQL语句。我从未在SQL中编写if语句,但我希望逻辑能够像这样工作:

SELECT Table3.ID3, Table1.Process1, Table2.Process2, Table3.Process3
FROM (IF Table1.ID = Table3.IDfromPrevious Then Table1 INNER JOIN Table3 ON Table1.ID = Table3.IDfromPervious ELSE Table2.ID2 = Table3.IDfromPrevious Then Table2 INNER JOIN Table3 ON Table2.ID2 = Table3.IDfromPervious)

3 个答案:

答案 0 :(得分:0)

MS Access仅支持标准ISO SQL的子集。经过几次尝试后,似乎只能通过子查询来实现。然后,该子查询可以使用Nz条件外部连接,如下所示:

SELECT    Table3.ID3, Table12.Process1, Table12.Process2, Table3.Process3
FROM       (SELECT    Table2.ID2, Table1.ID, Table1.Process1, Table2.Process2
            FROM      Table1
            LEFT JOIN Table2 ON Table2.ID = Table1.ID) AS Table12
LEFT JOIN Table3 ON Table3.IDfromPrevious =  Nz(Table12.ID2, Table12.ID)

答案 1 :(得分:0)

DECLARE @Table1 TABLE
(
ID INT
,Process1 VARCHAR(10)
)

INSERT INTO @Table1
VALUES
(1,'a')
,(2,'b')
,(3,'c')
,(4,'d')

DECLARE @Table2 TABLE
(
ID INT
,ID2 INT
,Process2 VARCHAR(10)
)

INSERT INTO @Table2
VALUES
(1,50,'e')
,(2,51,'f')
,(4,52,'g')



DECLARE @Table3 TABLE
(
IDfromPrevious INT
,ID3 INT
,Process3 VARCHAR(10)
)

INSERT INTO @Table3
VALUES
(50,500,'h')
,(51,501,'i')
,(52,502,'j')
,(3,503,'k')

SELECT * FROM @Table1
SELECT * FROM @Table2
SELECT * FROM @Table3


SELECT 
ID3
,Process1
,Process2
,Process3
FROM @Table1 T1
LEFT JOIN @Table2 T2 ON T1.ID = T2.ID
LEFT JOIN @Table3 T3 ON T3.IDfromPrevious IN (T2.ID2,T1.ID)

enter image description here

答案 2 :(得分:0)

以简单的方式完成,加入两个条件然后保持not NULL

select t3.ID3, isnull(t1.process1, tx.Process1) Process1, t2.Process2, t3.Process3
from t3
left join t2 on t3.IDfromPrevious = t2.ID2
left join t1 on t2.ID = t1.ID
left join t1 tx on t3.IDfromPrevious = tx.ID