0

我将使用存储在 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
4

3 回答 3

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 
于 2013-03-27T04:56:24.657 回答
0

我认为您在左连接之后添加一个选择会出现语法错误。我发现了一个带有更新的堆栈溢出帖子,也许您可​​以将其用作重新排列查询的示例: UPDATE multiple tables in MySQL using LEFT JOIN

于 2013-03-27T04:23:20.080 回答
0

我使用 rownum 解决了这个问题

UPDATE TABLE1 set TABLE1.COLUMN1 = (select T2.COLUMN1 from TABLE1 AS T2
where T2.PK = TABLE1.PK
and rownum = 1 )
于 2015-12-17T17:27:29.033 回答