Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从select更新查询数据时的MySQL查询语法(多行)_Mysql_Sql - Fatal编程技术网

从select更新查询数据时的MySQL查询语法(多行)

从select更新查询数据时的MySQL查询语法(多行),mysql,sql,Mysql,Sql,我想更新test1表,并从test2表中获取数据。我正在尝试使用JOIN,但它不起作用 我的问题是: UPDATE `test1` INNER JOIN `test2` ON `test2`.`where`=`test1`.`id` SET `test1`.`value`=`test1`.`value`+`test2`.`add` 我在test2中有两条记录,在test1中有一条记录 测试1: id => 1 value => 0 测试2: id => 1 where =&

我想更新
test1
表,并从
test2
表中获取数据。我正在尝试使用JOIN,但它不起作用

我的问题是:

UPDATE `test1` INNER JOIN `test2` ON `test2`.`where`=`test1`.`id` SET `test1`.`value`=`test1`.`value`+`test2`.`add`
我在
test2
中有两条记录,在
test1
中有一条记录

测试1:

id => 1
value => 0
测试2:

id => 1
where => 1
add => 1

id => 2
where => 1
add => 2
此查询的结果是
test1
value
=1,而不是3。这在SQL中是可能的吗

对不起我的英语

UPDATE test1 
SET test1.value = test1.value + test2.add
FROM test1 INNER JOIN test2 ON (test1.ID = test2.ID)
GO

我相信这就是你想要做的

您需要加入一个子查询,该子查询获取由
where
列分组的
add
列的总和。试试这个

UPDATE `test1` t1
INNER JOIN (
  SELECT `where`, SUM(`add`) as `add` FROM test2 GROUP BY `where`
) as t2
ON t1.id = t2.`where`
SET t1.`value` = t2.`add`

我不完全确定您想要完成什么,但您的“where”语句必须位于查询的末尾。更新(某物)->设置(某物)->在哪里(某物),而不是按照你所做的顺序。NewGuy,你为什么期望它是3?
test1
的唯一记录与
test2
的第一条记录合并,并且
test1.value
设置为0+1。Dorvalla,
其中
是列的名称。:)试着按照我下面展示的方式来写。我认为你是如何设置查询的令人困惑。你在test2.where.Olexa上以列的形式显示你的where,我的SQL不好,是的,这是事实,test1和test2的一条记录,我太傻了:(但我想在最后有3条。碎纸机解决方案正在工作,我期待这个结果