mysql在表中插入if empty else update

oyxsuwqo  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(370)

我想把数据放在另两个表的第三个表中。但如果用户已经存在,我只想更新用户点。我已经看了关于重复密钥更新的内容,但不明白如何在插入时实现它。

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
vcirk6k6

vcirk6k61#

我在插入后使用了duplicate key update points=点,但什么都没有发生。但是增加值(点)反而解决了问题。谢谢巴玛。

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)

相关问题