我要使用table_b中存储的变量更新table_a。但当我尝试使用选择查询进行更新时,我收到了错误,请帮助我。谢谢你。
这是2个表的结构:
CREATE TABLE IF NOT EXISTS `table_a` (
`fk1` int(11) DEFAULT NULL,
`avg_100` int(11) DEFAULT NULL,
`avg_score` int(11) DEFAULT NULL,
`cvg_date` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `table_b` (
`fk1` int(11) NOT NULL DEFAULT '0',
`avg_100` int(11) DEFAULT NULL,
`avg_score` int(11) DEFAULT NULL,
`cvg_date` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
当我尝试执行查询时
UPDATE table_a a LEFT JOIN ((
SELECT fk1, SUM(avg_100) as avg_100, SUM(avg_score) as avg_score, MAX(cvg_date) as cvg_date
FROM table_b
GROUP BY fk1
) AS b1 ) AS b ON a.fk1= b.fk1
SET
a.avg_score = b.avg_score,
a.avg_100 = b.avg_100,
a.cvg_date = b.cvg_date
我收到了一个错误:
[Err] 1064 - 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 'b ON a.fk1= b.fk1
SET
a.avg_score = b.avg_score,
a.avg_100 = b.avg_100,
' at line 4
答案 0 :(得分:1)
您正在为select返回的表设置别名“b”和“b1”。你只需要一个。试试这个问题:
UPDATE table_a a
LEFT JOIN (
SELECT fk1, SUM(avg_100) as avg_100, SUM(avg_score) as avg_score, MAX(cvg_date) as cvg_date
FROM table_b GROUP BY fk1
) AS b
ON a.fk1= b.fk1
SET
a.avg_score = b.avg_score,
a.avg_100 = b.avg_100,
a.cvg_date = b.cvg_date
答案 1 :(得分:0)
我认为你在左连接之后添加一个select会出现语法错误。 我发现了一个带有更新的堆栈溢出帖子,您可以将其用作重新排列查询的示例: UPDATE multiple tables in MySQL using LEFT JOIN
答案 2 :(得分:0)
我使用rownum
解决了这个问题UPDATE TABLE1 set TABLE1.COLUMN1 = (select T2.COLUMN1 from TABLE1 AS T2
where T2.PK = TABLE1.PK
and rownum = 1 )