使用CASE语句的嵌套SQL查询

时间:2011-01-26 16:15:46

标签: sql mysql

如何通过执行这两个查询(步骤)来编写一个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)

4 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

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

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)

答案 2 :(得分:1)

您不需要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;

答案 3 :(得分:0)

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

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