0

I want to put data in a third table based from two other tables. But if the user already exist I just want to update the users points. I've looked at ON DUPLICATE KEY UPDATE but don't understand how to implent it with my Insert.

INSERT INTO toplist( user_id, name, lastname, points )
SELECT O.user_id, name, lastname, SUM( points ) AS points
FROM userdata AS C, predictions AS O
WHERE O.lid =2020
AND C.user_id = O.user_id 
GROUP BY O.user_id
Anders
  • 63
  • 4
  • 1
    Google is your friend: https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html – Blue Jul 25 '18 at 20:15
  • You say you don't understand how to implement it: So why not show what you've tried already? – Blue Jul 25 '18 at 20:16
  • 2
    Possible duplicate of [Insert into a MySQL table or update if exists](https://stackoverflow.com/questions/4205181/insert-into-a-mysql-table-or-update-if-exists) – Progman Jul 25 '18 at 20:16
  • `ON DUPLICATE KEY UPDATE` should work. Show what you tried, and we can help you fix it. – Barmar Jul 25 '18 at 20:27
  • `ON DUPLICATE KEY UPDATE points = VALUES(points)` – Barmar Jul 25 '18 at 20:27
  • I used ON DUPLICATE KEY UPDATE points = points after my Insert and nothing happend. But adding VALUES(points) instead it solved the problem. How to mark your answer right Barmar? – Anders Jul 25 '18 at 20:47

1 Answers1

0

I used ON DUPLICATE KEY UPDATE points = points after my Insert and nothing happend. But adding VALUES(points) instead it solved the problem. Thanks Barmar.

   INSERT INTO toplist( user_id, name, lastname, points )
    SELECT O.user_id, name, lastname, SUM( points ) AS points
    FROM userdata AS C, predictions AS O
    WHERE O.lid =2020
    AND C.user_id = O.user_id 
    GROUP BY O.user_id
    ON DUPLICATE KEY UPDATE points = VALUES(points)
Anders
  • 63
  • 4