Table Values()用于更新多行的构造方法

问题描述 投票:0回答:3

我刚刚将一个应用程序从我使用Postgres的本地实例移动到Google Compute Engine虚拟实例,我在其中使用基于MySQL构建的Google Cloud SQL。

自从移动以来,这个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)"
mysql postgresql google-cloud-sql
3个回答
1
投票

你应该能够用这样的东西取代(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>

0
投票

您可以创建一个临时表来在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, ...)

0
投票

使用简单更新:

UPDATE events 
SET photographers = 2
WHERE id = 1;

MySql不支持PostgreSql的非标准语法。


如果需要多个值,可能会使用多表更新语法: qazxsw poi

http://dev.mysql.com/doc/refman/5.7/en/update.html

一种选择是将值插入临时表 - 如@Denis所写 - 然后执行更新:

UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]

另一种选择是 - 作为@Razvan Musaloiu-E。写道 - 使用union构建动态查询:

UPDATE table t, temporary_table tmp
SET t.photographers = tmp.photographers
WHERE t.id = tmp.id
© www.soinside.com 2019 - 2024. All rights reserved.