MySQL更新与在哪里加入

时间:2019-05-23 15:31:47

标签: mysql sql

我尝试了不同的方法,但无法弄清楚需要在何处放置括号以及如何正确执行此查询。

我得到的错误是:

  

错误1093(HY000):您无法在FROM子句中指定目标表'tb1'用于更新

代码:

    UPDATE tb1
SET company_id=258
WHERE id IN
    (SELECT c.well_id container_well_id
     FROM tb2 b
     INNER JOIN tb3 c ON b.id = c.id
     INNER JOIN tb1 w ON w.id = c.well_id
     WHERE b.id_number IN (2609,
                           4279,
                           4082,
                           4083,
                           4117,
                           3818,
                           3154,
                           3813,
                           3822,
                           3819)
       AND c.company_id = 258
       AND w.company_id = 259 );

2 个答案:

答案 0 :(得分:1)

一种方法是改用join

UPDATE tb1 JOIN
       (SELECT c.well_id container_well_id
        FROM tb2 b JOIN
             tb3 c ON b.id = c.id JOIN
             tb1 w ON w.id = c.well_id
        WHERE b.id_number IN (2609, 4279, 4082, 4083, 4117, 3818, 3154, 3813, 3822, 3819
                             ) AND
              c.company_id = 258 AND
              w.company_id = 259
        ) x
        ON x.container_well_id = tb1.id
    SET company_id = 258;

答案 1 :(得分:1)

只需添加外部选择即可嵌套当前子查询:

UPDATE tb1
SET company_id=258
WHERE id IN
  (SELECT t.container_well_id FROM
    (SELECT c.well_id container_well_id
     FROM tb2 b
     INNER JOIN tb3 c ON b.id = c.id
     INNER JOIN tb1 w ON w.id = c.well_id
     WHERE b.id_number IN (2609,
                           4279,
                           4082,
                           4083,
                           4117,
                           3818,
                           3154,
                           3813,
                           3822,
                           3819)
       AND c.company_id = 258
       AND w.company_id = 259 ) t
  );