SQL 服务器条件连接

SQL Server Conditional Joins

我有三个表 Table1 Table2 Table3。我必须对它们执行一些操作并将结果存储在 Table4

表 1:

ID       t1col2     t1col3  
``````   ``````     ``````
123      Fname1     Lname1
456      Fname2     Lname2  
789      Fname3     LnameAA  

表 2:

ID        t2col2     t2col3     t2col4
`````     ``````     ``````     ``````
122       Fname1     Lname1     String1
466       Fname2     Lname2     String2
789       Fname3     Lname3     String3  

表 3:

ID       t3col2       
``````   ``````      
122      querty     
789      asdfgh 

如何执行条件联接以检查以下条件:

预期输出:

表 4:

ID         t1col2     t2col3     t2col4     t3col2  
```````    ```````    ```````    ```````    ```````  
789        Fname3     Lname3     String3    asdfgh
Select Table1.ID, Table1.T1col2, Table2.T2col3, Table2.T2col4, Table3.T3col2
From Table1
Inner join Table2 on Table1.ID = Table2.ID AND Table1. t1col3 like ‘%AA%’ 
Inner join Table3 on Table1.ID = Table3.ID 

抱歉,但我不明白您想要什么:« 如果找到,仅当 Table1 ID 和 Table2 ID 相同时,将 Table1 中的 t1col3 值替换为 Table2 中的 t2col3 值。 » 你想更新 table1 上的值吗?

你能试试这个吗

SELECT T1.ID , T1COL2, T2COL3, T2COL4, T3COL2
FROM TABLE2 AS T2
INNER JOIN TABLE1 AS T1 
  ON T2.ID = T1.ID AND T1.T1COL3 LIKE '%AA' 
INNER JOIN TABLE3 AS T3
  ON T3.ID = T2.ID

Fiddle Link

首先将它们插入表4。

然后根据表4修改表1。

DELETE FROM Table4;

INSERT INTO Table4 (ID, t1col2, t2col3, t2col4, t3col2)
SELECT t2.ID, t1.t1col2, t2.t2col3, t2.t2col4, t3.t3col2
FROM Table2 t2
JOIN Table1 t1 ON t1.ID = t2.ID AND t1.t1col3 LIKE '%AA%'
JOIN Table3 t3 ON t3.ID = t1.ID;

UPDATE t1
SET t1col3 = t4.t2col3
FROM Table1 t1
JOIN Table4 t4 ON t4.ID = t1.ID
WHERE t1.t1col3 != t4.t2col3;

SELECT * 
FROM Table4 
ORDER BY ID;

测试 db<>fiddle here

结果:

ID      t1col2      t2col3      t2col4      t3col2
----    --------    --------    --------    --------
789     Fname3      Lname3      String3     asdfgh