2

我正在尝试更新数据库中的特定列。

此查询有效:

UPDATE table1 A INNER JOIN table2 B 
ON A.type = B.typeName
SET A.closed = 0, A.sample = 0 
WHERE A.`status` IN ('Finished', 'Exception', 'Query') AND A.date BETWEEN '2013-01-01' AND '2013-01-31' 
AND A.code IN ('ex1','ex2','ex3') 
AND A.closed = 0 AND B.order = 'Non-Order' AND A.userName = 'test';

但是当我试图设定一个限制时,它说:

Incorrect usage of UPDATE and LIMIT

UPDATE table1 A INNER JOIN table2 B 
ON A.type = B.typeName
SET A.closed = 0, A.sample = 0 
WHERE A.`status` IN ('Finished', 'Exception', 'Query') AND A.date BETWEEN '2013-01-01' AND '2013-01-31' 
AND A.code IN ('ex1','ex2','ex3') 
AND A.closed = 0 AND B.order = 'Non-Order' AND A.userName = 'test' LIMIT 3;

如何使用限制进行此更新?多谢!

[EDIT]

我已经做了我想做的事,但是速度很慢,需要 6 秒才能更新 3 行。

这是查询:

UPDATE table1 SET closed=1, sample=1
 WHERE id IN (
     SELECT id FROM (
         SELECT id FROM table1 A
         INNER JOIN table2 B ON A.type = B.typeName
         WHERE A.`status` IN ('Finished', 'Exception', 'Query') AND A.date BETWEEN '2013-01-01' AND '2013-01-31' 
    AND A.code IN ('ex1','ex2','ex3') 
    AND A.closed = 0 AND B.order = 'Non-Order' AND A.userName = 'test' LIMIT 3
     ) tmp
 );

我怎样才能优化这个查询再次感谢!

4

2 回答 2

5

你就是不能。

根据UPDATE 的 MySQL 文档

For the multiple-table syntax, UPDATE updates rows in each table named in
table_references that satisfy the conditions. In this case, ORDER BY and LIMIT
cannot be used. 

更新 1

UPDATE  table1 a
        INNER JOIN
        (
            SELECT  id 
            FROM    table1 A
                    INNER JOIN table2 B 
                        ON A.type = B.typeName
            WHERE   A.status IN ('Finished', 'Exception', 'Query') AND 
                    A.date BETWEEN '2013-01-01' AND '2013-01-31' AND 
                    A.code IN ('ex1','ex2','ex3') AND 
                    A.closed = 0 AND 
                    B.order = 'Non-Order' AND 
                    A.userName = 'test' 
            LIMIT   3
        ) tmp ON a.ID = tmp.ID
SET     a.closed = 1, 
        a.sample = 1
于 2013-02-28T05:35:15.973 回答
1

LIMIT只能用于SELECT语句。如果你想限制没有。对于您的 UPDATE 语句受影响的记录,您必须使用 WHERE。

于 2013-02-28T05:35:34.043 回答