更新WHERE字段IN

时间:2013-06-03 17:34:50

标签: mysql sql select sql-update

我有这个有用的查询:

SELECT idVendRigMov
FROM VendRM
WHERE idArtPromo IS NULL AND
      (idArtCategoria NOT IN (SELECT idArtCategoria FROM VendScontiCatEscl WHERE idVendSconti=2) OR idArtCategoria IS NULL) AND idVendTesMov=1

返回“idVendRigMov”列表;

我需要对此结果的每一行进行更新,如下所示:

UPDATE VendRigMov SET Sconto='7' WHERE idVendRigMov IN (result of previous query);

我试过这个:

UPDATE VendRigMov SET Sconto='7' WHERE idVendRigMov IN 
(
SELECT idVendRigMov FROM VendRM WHERE idArtPromo IS NULL AND (idArtCategoria NOT IN (SELECT idArtCategoria FROM VendScontiCatEscl WHERE idVendSconti=2) OR 
idArtCategoria IS NULL) AND idVendTesMov=1
)

但是我得到了这个错误: “表”VendRM“的定义阻止了表'VendRigMov'上的操作UPDATE”

我该如何进行此查询?

1 个答案:

答案 0 :(得分:1)

VendRM可能是一个引用表VendRigMov的视图。如果是这样,您可以通过使用其他级别的子查询来解决此问题。您的查询是:

UPDATE VendRigMov
    SET Sconto = '7'
    WHERE idVendRigMov IN (SELECT idVendRigMov
                           FROM VendRM
                           WHERE idArtPromo IS NULL AND
                                 (idArtCategoria NOT IN (SELECT idArtCategoria
                                                         FROM VendScontiCatEscl
                                                         WHERE idVendSconti=2) OR 
                                                               idArtCategoria IS NULL
                                                        ) AN
                                idVendTesMov=1
                          )

这应该有效:

UPDATE VendRigMov
    SET Sconto = '7'
    WHERE idVendRigMov IN (select idVendRigMov
                           from (SELECT idVendRigMov
                                 FROM VendRM
                                 WHERE idArtPromo IS NULL AND
                                       (idArtCategoria NOT IN (SELECT idArtCategoria
                                                               FROM VendScontiCatEscl
                                                               WHERE idVendSconti=2) OR 
                                                                     idArtCategoria IS NULL
                                                              ) AN
                                      idVendTesMov=1
                                ) t
                          )

这迫使MySQL实例化子查询。实例化时,您不再有在子查询中立即访问外部引用表的问题。