内部联接和更新

时间:2017-05-28 02:30:44

标签: sql

我有一个table1,如下所示

user_ID country  status  role
-------- ------ ------- -----
keshav   SG        Active  Admin
Bargav   IN        Active  Subuser
Sanvi     GB       Active   subuser
yellin    CN       Active    subuser

我有另一个表stage_table,如下所示

user_ID  country   role 
-------  -------  ------
keshav     SG      Admin
Sanvi      GB      subuser
Manav      IN      subuser 

我想基于stage_table更新table1。正如你所看到的,stage_table没有Bargav记录,所以我想更新table1 Bargav行,状态为" InActive"和Manav条目是新的,所以更新它,状态为" Active"。因此table1应如下所示

user_ID  country  status Role 
-------  -------  ------  -----
keshav   SG        Active  Admin
Bargav   IN        InActive  Subuser
Sanvi     GB       Active   subuser
yellin    CN       Active    subuser
Manav     In       Active    subuser

我正在考虑使用如下的内连接,这是正确的吗?我没有得到理想的结果..因为我不知道如何同时进行合并和更新

select * 
from table1 
inner join stage_table on table1.user_ID = stage_table.user_ID 
                       and (update table.status ="InActive" 
                            where table1.user_Id != stage_table.user_ID) 

请帮忙。

2 个答案:

答案 0 :(得分:0)

MySQL / Mariadb和(我认为)SQLite将使用传统的SQL结构,如下所示,您需要将插入和更新作为单独的查询进行:

INSERT INTO table1 (user_ID, country, status, role)
SELECT t2.user_ID, t2.country,'Active' as Status, t2.role 
FROM table2 t2
LEFT JOIN table1 t1 ON t1.user_id = t2.user_id
WHERE t1.user_id IS NULL
;

UPDATE  table1 t1
LEFT JOIN table2 t2 ON t1.user_id = t2.user_id
SET t1.status = CASE WHEN t2.user_id IS NULL THEN 'InActive' ELSE 'Active' END
;

答案 1 :(得分:0)

在MS SQL Server中,您可以分别使用以下两个查询进行更新和插入 -

-- For Update
UPDATE T1
SET T1.[STATUS] = (
    CASE 
        WHEN T2.[USER_ID] IS NULL
            THEN 'INACTIVE'
        ELSE T1.[STATUS]
        END
    )
FROM TABLE1 T1
LEFT OUTER JOIN STAGE_TABLE T2 ON T1.[USER_ID] = T2.[USER_ID];

-- For Insert
INSERT INTO TABLE1 (
    [USER_ID]
    ,COUNTRY
    ,[STATUS]
    ,[ROLE]
    )
SELECT T2.[USER_ID]
    ,T2.COUNTRY
    ,'Active'
    ,T2.[ROLE]
FROM TABLE1 T1
RIGHT OUTER JOIN STAGE_TABLE T2 ON T1.[USER_ID] = T2.[USER_ID]
WHERE T1.[USER_ID] IS NULL;