简体   繁体   English

SQL查询更新字段取决于子查询

[英]SQL Query Update field depending on subquery

I need a SQL Query. 我需要一个SQL查询。 My Table users has 3 fields: Name, iduser, idgroup. 我的表用户有3个字段:名称,iduser,idgroup。

One user can appear many times on the same table with same iduser and different idgroups. 一个用户可以使用相同的iduser和不同的idgroup在同一张表上多次出现。

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. 如果不存在具有给定iduser和idgroup的行,则必须将其作为新行插入。

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? 我的SQL查询sintax错误,因此我无法使用它,您将如何实现我的需求?

I'm using mySQL database (managed with phpmyadmin) and doing the insert from a lua script. 我正在使用mySQL数据库(由phpmyadmin管理),并通过lua脚本进行插入。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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