检查创建重复以进行软删除

时间:2017-11-14 14:36:44

标签: mysql mariadb

我有一个名为country的数据库表。每个国家/地区都有名称和删除列。当用户使用名称创建新国家/地区时,将创建一个名称与删除的默认值为0的新行。我创建了名称和删除列的唯一索引。

我现在想要的是能够创建具有名称的新行并且唯一地删除0并且还将更新替换为删除1或更新已删除0的现有行。

INSERT INTO country (name, removed) VALUES ('United State',0) ON DUPLICATE KEY UPDATE name = VALUES(name), removed = 1
SELECT name FROM country WHERE removed = 1

条件

// If name doesn't exists in db, create new row with new name and removed 0
// If name exists in db, check for removed 1 for existing name:
            // If found, replace the new one with that removed 1 with removed 0
       // else replace the new one with that removed 0 (Works like upsert)

1 个答案:

答案 0 :(得分:0)

您似乎有UNIQUE(name, removed)。但这意味着每个国家可以有2行?也许你只想要PRIMARY KEY(name)。这将允许IODKU(也称为Upsert)仅基于name