我有两张桌子
表1:
table 2
process status
1 completed
2 completed
3 not completed
;是一个从table1
Process status
1 completed
2 completed
3 not completed
3 completed
下次当数据从表1推入历史表时,我只想要推送状态为“未完成”的数据
这样我的历史记录表如下所示
表2(历史表)
INSERT INTO table2
SELECT *
FROM table1
WHERE NOT (status IN (SELECT Status
FROM table2
WHERE status = 'completed'))
请帮我解决这个问题,我已经尝试了子查询,但它不适合我。
我使用了这个查询:
{{1}}
答案 0 :(得分:1)
试试这个。
INSERT INTO table2 (process,status)
select process,'completed' as status From table1 where process in
(select distinct process from table2 where status <> 'completed')
答案 1 :(得分:0)
AFAI理解您的问题,您需要更新已从不完整状态变为完成状态的流程状态(假设流程从不完整到完整是线性的)。
INSERT INTO table2 (process,status)
SELECT
T1.process as process,
CASE T1.state WHEN 0 THEN 'not completed ' ELSE 'completed' END as status
FROM
(SELECT process, MAX(CASE WHEN status = 'not completed' THEN 0 WHEN status ='completed' THEN 1 END) state from table1 group by process) T1
LEFT JOIN
(SELECT process, MAX(CASE WHEN status = 'not completed' THEN 0 WHEN status ='completed' THEN 1 END) state from table2 group by process) T2
ON T1.process=T2.process
WHERE T2.process is NULL OR T2.state<> T1.state
答案 2 :(得分:0)
如果要在表中的两者中匹配某些列,请使用此选项:
更新_table_name_ SET col1 = _alias_table_.col1,...(除合并键和Identity列以外的所有列) FROM(选择*来自_tmp_table1_ UNION SELECT *来自_tmp_table2_)_alias_table_ _table_name _._ merge_key_ = _alias_table _._ merge_key_(可以是多个合并键)
示例: 更新订单详细信息 设置产品名称= a。产品名称 来自(从产品中选择productid,productname)作为 加入订单详细信息 在o.productid = a.productid上 其中a.productid = o.productid;