2011-01-26 259 views
1

我怎么能写只是一个SQL查询来获取相同的结果通过执行这两个查询(步骤):嵌套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

我觉得这是你描述:

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`join`比`table1,table2`更具可读性:) – Andomar 2011-01-26 16:31:04

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) 
0

您可以使用临时表来存储德第一次查询的结果,然后resuse数据在第二个查询。

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 
+0

正如你可以在其他的答案看是没有必要的时间表。此外,我只要求1个查询语句。无论如何,你的回答使用3。 – texai 2011-01-26 16:32:02

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; 
+0

+1在末尾添加`和flag = 1`,这是可行的。好的短版。 – Andomar 2011-01-26 16:26:51