繁体   English   中英

使用CASE语句的嵌套SQL查询

[英]Nested SQL query using CASE statements

如何通过执行以下两个查询(步骤),仅编写一个SQL查询来获得相同的结果:

第一步:

SELECT old_id, new_id FROM history WHERE flag = 1;

结果:

+--------+--------+
| old_id | new_id |
+--------+--------+
|     11 |     22 |
|     33 |     44 |
|     55 |     66 |
+--------+--------+

然后,使用以前的结果,执行以下查询:

UPDATE other_tabla SET somefk_id = CASE somefk_id
    WHEN 11 THEN 22
    WHEN 33 THEN 44
    WHEN 55 THEN 66
END WHERE somefk_id IN (11,33,55)

我认为这就是您所描述的:

UPDATE `other_tablea`
JOIN `history` ON history.old_id = other_tablea.somefk_id AND history.flag = 1
SET other_tablea.somefk_id = history.new_id

子查询似乎可以解决问题:

update  other_tabla
set     somefk_id = coalesce((
            select  new_id 
            from    history 
            where   flag = 1 
                    and old_id = other_tabla.somefk_id
        ), other_tabla.somefk_id)

你不需要case

update
  other_table, history 
set
  other_table.somefk_id=history.new_id
where 
  other_table.somefk_id=history.old_id and history.flag=1;

您可以使用临时表存储第一个查询的结果,然后在第二个查询中重新使用数据。

SELECT old_id, new_id 
INTO #tmpTable1
FROM history 
WHERE flag = 1;

UPDATE other_tabla SET somefk_id = t.new.id
FROM other_tabla as o
INNER JOIN #tmpTable1 t ON o.somefk_id=t.old_id

DROP TABLE #tmpTable1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM