-1

I need to insert information to DB, but if information "user_id" already exist update, like this: (the problem is user_id isn't the KEY)

INSERT INTO access_token 
        (id,access_token,user_id)
VALUES
        (1062371433,106237146,10623714)
ON DUPLICATE user_id     <=== receive error in this line
        UPDATE
            access_token = VALUES(access_token)

but receive error in line 5,

how to fix it?

thanks,

mwafi
  • 3,946
  • 8
  • 56
  • 83
  • possible duplicate of [Insert to table or update if exists (MySQL)](http://stackoverflow.com/questions/4205181/insert-to-table-or-update-if-exists-mysql) – Hamatti Sep 24 '14 at 06:44
  • Maybe the link below will help you Click [here]:http://stackoverflow.com/questions/6382806/django-save-update-on-duplicate-key – Tangoo Sep 24 '14 at 06:44
  • 1
    Sounds like you might need a unique constraint on `user_id`? Then update your syntax to `ON DUPLICATE KEY`... – sgeddes Sep 24 '14 at 06:44
  • @Hamatti the problem is "user_id" isn't the table KEY and not unique – mwafi Sep 24 '14 at 06:50
  • I think on Insert on duplicate key update is what you should be looking for. – Bhoj Raj Bhatta Sep 24 '14 at 06:55
  • 1
    you can't do it by on duplicate because it is not a key So, you have to do it manually – nesreen Sep 24 '14 at 07:15

2 Answers2

0
set @founded_id=(select user_id from access_token  where user_id='10623714');


if(@founded_id='10623714')then
update access_token  set ............

else
INSERT INTO access_token 
        (id,access_token,user_id)
VALUES
        (1062371433,106237146,10623714)
nesreen
  • 201
  • 2
  • 14
0

You could use this:

INSERT ON DUPLICATE KEY UPDATE

INSERT INTO access_token 
    (id,access_token,user_id)
VALUES
    (1062371433,106237146,10623714)
ON DUPLICATE KEY
    UPDATE
        access_token = VALUES(access_token);
Neels
  • 2,547
  • 6
  • 33
  • 40