0

I have the table behaviour where I count the pages of each hash. I want to transfer the results into a new table new_table. If the hash on new_table exists, then just update the number of pages. Otherwhise, if it is a new hash found on behaviour that did not inserted yet to new_table just add it.

INSERT INTO new_table (hash, pages)
SELECT hash, COUNT( id ) AS pages
FROM behaviour
ON DUPLICATE KEY UPDATE new_table.pages=behaviour.pages
GROUP BY hash

I get an error on the 5th line "group by hash". What am I doing wrong?

#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 'GROUP BY hash' at line 5

Panda
  • 6,955
  • 6
  • 40
  • 55
villoui
  • 245
  • 1
  • 3
  • 11

2 Answers2

0
INSERT INTO new_table (hash, pages)
SELECT hash, COUNT( id ) AS pages
FROM behaviour
ON DUPLICATE KEY UPDATE new_table.pages=behaviour.pages
GROUP BY hash;

Try this

Priyanshu
  • 885
  • 6
  • 12
0

Use the below query. This will work

INSERT INTO new_table (hash, pages)
SELECT hash, COUNT( id ) AS pages
FROM behaviour GROUP BY hash
ON DUPLICATE KEY UPDATE pages=VALUES(pages)

You Must add the group by clause before the on duplicate key check

Andrews B Anthony
  • 1,381
  • 9
  • 27
  • maybe the problem is because the COUNT( id ) AS pages from behaviour is not passed to the new_table.pages as a number – villoui Apr 26 '16 at 09:23