简体   繁体   中英

SQL Query Update field depending on subquery

I need a SQL Query. My Table users has 3 fields: Name, iduser, idgroup.

One user can appear many times on the same table with same iduser and different idgroups.

Field Name should update to new value if it has changed.

If there no exists a row with given iduser and idgroup it has to be inserted as a new row.

IF EXISTS(SELECT 1 FROM users WHERE iduser=3 AND idgroup=4)
BEGIN
     UPDATE users SET Name='New Name' WHERE iduser=3 AND idgroup=4
END
ELSE
     INSERT INTO users VALUES('Name',5,3)
END

My SQL Query sintax is wrong so I can't use it, how would you achieve what I need?

I'm using mySQL database (managed with phpmyadmin) and doing the insert from a lua script.

You need to make sure you have the right unique keys in place.

ALTER TABLE users ADD UNIQUE `unique_index`(`iduser`, `idgroup`);

Then, you should be able to run this insert/update:

INSERT INTO users (Name, iduser, idgroup) 
VALUES ('name value',5,3) 
ON DUPLICATE KEY UPDATE Name = VALUES(Name) WHERE Name <> VALUES(Name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM