我正在尝试在表中插入新记录,我有两列
user_records
------------------------
| Attribute | Datatype |
|------------------------|
| user_id | varchar(25)|
| count | int |
------------------------
查询:
INSERT into user_records Values("nix_1", 0)
但如果用户已经存在,那么它应该将计数增加1
答案 0 :(得分:0)
在尝试INSERT
之前,您将检查记录是否存在。您的查询应符合以下内容。示例适用于SQL Server。
DECLARE @sUserID VARCHAR(25) = "nix_1"; // This should be the parameter passed on into the stored procedure
IF EXISTS(SELECT user_id FROM WHERE user_id = @sUserID)
// Increase the count
UPDATE user_records SET count = count + 1
WHERE user_id = @sUserID
ELSE
// Insert new record
INSERT INTO user_records Values (@sUserID , 0)
有关EXIST
答案 1 :(得分:0)
为什么不使用INSERT ... ON DUPLICATE KEY
语法?
INSERT INTO user_records (user_id, count) VALUES ('nix_1', 0)
ON DUPLICATE KEY UPDATE count = count + 1;
http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html