我刚刚将一个应用程序从我使用Postgres的本地实例移到了虚拟实例,在那里我使用了构建在MySQL上的。
自从移动之后,这个SQL查询就不再工作了:
"UPDATE events e SET e.photographers = up.photographers FROM (VALUES "+ value_pairs +") AS up(id, photographers) WHERE up.id = e.id"其中value_pairs = (1,2)
这是我所看到的确切错误:
error running query { [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (VALUES (1,2)) AS up(id, photographers) WHERE up.id = e.id' at line 1]
输出似乎是正确的..。有人看到我做错什么了吗?
更新/解决方案应该已经澄清,value_pairs可以增长为多个值,即(4,2),(6,1),(10,3),.
由于这个查询的性质相对简单,我最后使用了一个使用INSERT子句的ON DUPLICATE KEY查询:
("INSERT INTO events (id,photographers) VALUES "+ value_pairs + "ON DUPLICATE KEY UPDATE photographers=VALUES(photographers)"发布于 2014-01-02 15:52:21
您应该能够将(VALUES "+ value_pairs +") AS up(id, photographers)替换为如下所示:
mysql> (SELECT 1 AS photographers, 2 AS id) UNION (SELECT 3, 4) UNION (SELECT 5, 6);
+---------------+----+
| photographers | id |
+---------------+----+
| 1 | 2 |
| 3 | 4 |
| 5 | 6 |
+---------------+----+
3 rows in set (0.00 sec)
mysql>发布于 2014-01-01 22:24:46
使用简单的更新:
UPDATE events
SET photographers = 2
WHERE id = 1;MySql不支持PostgreSql的非标准语法。
如果需要多个值,则可以使用多表更新语法:
http://dev.mysql.com/doc/refman/5.7/en/update.html
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]一种选择是向临时表插入值--正如@Denis所写的--然后执行更新:
UPDATE table t, temporary_table tmp
SET t.photographers = tmp.photographers
WHERE t.id = tmp.id另一种选择是- as @Razvan Musaloiu-E.编写-使用union构建一个动态查询:
UPDATE table t, (
SELECT 1 AS id, 2 AS photographers
UNION
SELECT 5, 7
UNION
SELECT 15, 67
UNION
.....
.....
.....
.....
UNION
SELECT 234, 567
) AS tmp
SET t.photographers = tmp.photographers
WHERE t.id = tmp.id发布于 2014-01-02 00:30:34
您可以创建一个临时表,以便在MySQL中运行查询:
create temporary table src ...
insert into src values ...然后使用src运行您的更新。它不像您当前使用的匿名临时表那么漂亮,但它会工作的。
另一种方法是使用一个巨大的案例陈述:
update events
set photographers = case id
when 1 then 2
...
end
where id in (1, ...)https://stackoverflow.com/questions/20873439
复制相似问题