0

I am going update table_a with variable stored in table_b. but when i trying update with select query, i got errors, please help me. Thank you alot.

This is struct of 2 tables:

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;

and when i try execute query

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

i got a error:

[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
Mr Jerry
  • 1,686
  • 3
  • 14
  • 22

3 Answers3

1

You are setting alias "b" and "b1" to the table returned by select. You just need one. Try this query:

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 
Eddie
  • 427
  • 3
  • 8
0

I think you have a syntax error by adding a select just after the left join. I found a stack overflow post with a update that maybe you could use as example to rearrange your query: UPDATE multiple tables in MySQL using LEFT JOIN

Community
  • 1
  • 1
ThaisK
  • 365
  • 1
  • 4
  • 22
  • "adding a select just after the left join" i think it is correct because i save select results as table – Mr Jerry Mar 27 '13 at 04:33
0

I solved this problem using rownum

UPDATE TABLE1 set TABLE1.COLUMN1 = (select T2.COLUMN1 from TABLE1 AS T2
where T2.PK = TABLE1.PK
and rownum = 1 )