MySQL从同一个表中选择并更新多行

时间:2015-07-01 21:31:42

标签: mysql sql select sql-update mysql-error-1093

通常我想从我的数据库中的*** Fetching SwiftyJSON *** Fetching Alamofire *** Checking out Alamofire at "1.2.3" *** Checking out SwiftyJSON at "2.2.0" *** xcodebuild output can be found in /var/folders/8n/044rh7_j6nlcdtsb3cgp_snc0000gn/T/carthage-xcodebuild.log *** Building scheme "Alamofire iOS" in Alamofire.xcworkspace A shell task failed with exit code 65: ** BUILD FAILED ** The following build commands failed: CompileSwift normal x86_64 [project root]/Carthage/Checkouts/Alamofire/Source/Request.swift CompileSwift normal x86_64 [project root]/Carthage/Checkouts/Alamofire/Source/ResponseSerialization.swift CompileSwift normal x86_64 [project root]/Carthage/Checkouts/Alamofire/Source/Manager.swift CompileSwift normal x86_64 [project root]/Carthage/Checkouts/Alamofire/Source/Alamofire.swift CompileSwift normal x86_64 [project root]/Carthage/Checkouts/Alamofire/Source/Validation.swift CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler 表中选择在某个日期之后创建的行,然后将所有选定行的orders字段更新为特定值office_id 。 我的MySQL版本是5.5.43。 在第一次,我试图将它放在一个SQL语句中,如下所示:

12

我收到了错误:UPDATE `order` SET office_id = 12 WHERE id IN ( SELECT id FROM `order` WHERE created_at >= DATE_FORMAT( '2014-07-02 00:00:00', '%Y.%m.%d 00:00:00' ) );

接下来,我尝试使用#1093 - You can't specify target table 'order' for update in FROM clause语句执行此操作,如下所示:

SELECT .. FOR UPDATE

哪个有效,但如果START TRANSACTION; SELECT id FROM `order` WHERE created_at >= DATE_FORMAT( '2014-07-02 00:00:00', '%Y.%m.%d 00:00:00' ) FOR UPDATE; UPDATE `order` SET office_id = 12 WHERE id IN ( id ); COMMIT; 语句没有返回任何行,那么SELECT .. FOR UPDATE将应用于office_id = 12表中的所有行,这是我绝对不想要的。

我正在寻找帮助修改第一或第二个适合工作的解决方案。

2 个答案:

答案 0 :(得分:2)

它比你制作它简单得多。您可以将WHERE子句直接应用于UPDATE语句。

UPDATE `order`
    SET office_id = 12
    WHERE created_at >= DATE_FORMAT( '2014-07-02 00:00:00', '%Y.%m.%d 00:00:00' );

答案 1 :(得分:1)

如果id中可以复制order,那么您可以使用join来表达查询:

UPDATE `order` o JOIN
       (SELECT distinct o.id
        FROM  `order` o
        WHERE created_at >= DATE_FORMAT( '2014-07-02 00:00:00', '%Y.%m.%d 00:00:00' 
       ) oo
       ON o.id = oo.id
    SET o.office_id = 12;