Mysql UPDATE查询SET从另一个查询的结果

时间:2018-01-05 19:31:54

标签: mysql sql-update subquery

我坚持这个.. 我已经提出了一个问题......

    SELECT ID_Rollo, ID_Rollo_Original
FROM 
    interpretes 
    LEFT JOIN (
        SELECT ID_Rollo_Original, ID_Rollo, count(ID_Rollo) as count
        FROM rollooriginal 
        GROUP BY rollooriginal.ID_Rollo
        HAVING count = 1
    ) rollooriginal ON  interpretes.ID_Programa = rollooriginal.ID_Rollo
WHERE 
interpretes.ID_Prog IS NULL AND ID_Rollo IS NOT NULL

给我回复:

ID_Rollo:  ID_Rollo_Original
78 ------- 656
88 ------- 5012

另一方面,我有一个表解释与一些cols。

ID_table: ID_Programa: ID_Prog: etc: etc:
1 ------- 78 -------- NULL ------
2 ------- 88 -------- NULL ------
3 ------- 642 ------- 2108 ------
etc....

在某些情况下,ID_Prog为NULL,我需要做的是创建查询以更新表解释,并在ID_Prog为空时将ID_Rollo_Original的结果复制到ID_Prog。

请注意,查询中的ID_Rollo和解释中的ID_Programa是等于。

预期

ID_table: ID_rollo: ID_Prog: etc: etc:
1 ------- 78 ------ 656 ------
2 ------- 88 ------ 5012 ------

像这样......

  

UPDATE解释SET interpretes.ID_Prog =(ID_Rollo_Original)WHERE   interpretes.ID_Programa =(RESULT ID_Rollo)AND interpretes.ID_Prog IS   NULL

1 个答案:

答案 0 :(得分:1)

可以使用带子查询的连接

UPDATE interpretes  a 
INNER  JOIN (
    SELECT ID_Rollo, ID_Rollo_Original
    FROM interpretes 
    LEFT JOIN (
            SELECT ID_Rollo_Original, ID_Rollo, count(ID_Rollo) as count
            FROM rollooriginal 
            GROUP BY rollooriginal.ID_Rollo
            HAVING count = 1
        ) rollooriginal ON  interpretes.ID_Programa = rollooriginal.ID_Rollo
    WHERE interpretes.ID_Prog IS NULL AND ID_Rollo IS NOT NULL
  ) T on t.ID_ROLLO = a.ID_ROLLO 
  SET a.ID_Prog = t.ID_Rollo_Original
  WHERE a.ID_Prog is NULL