[英]Insert row into table if column value does not already exist in table
I have the following query: 我有以下查询:
INSERT INTO LICENSE_TABLE
(code, license_type, distributor)
values ("uniquecode", "standard", "walmart")
I want to insert the row only if no row exists that already has code="uniquecode"
我只想在不存在已经具有
code="uniquecode"
的行的情况下插入行
How can I do this? 我怎样才能做到这一点?
I found some solutions involving INSERT IGNORE
, something about DUAL
, and a few more, but I did not understand which applies to my situation. 我找到了一些涉及
INSERT IGNORE
解决方案,有关DUAL
以及其他一些解决方案,但是我不知道哪种解决方案适用于我的情况。
If it matters, I am using pymysql
. 如果有关系,我正在使用
pymysql
。
The best way to do this uses on duplicate key update
: 最好的方法是
on duplicate key update
:
First, you need a unique index, so the database maintains the data integrity. 首先,您需要一个唯一索引,以便数据库维护数据完整性。
Second: 第二:
INSERT INTO LICENSE_TABLE (code, license_type, distributor)
VALUES ('uniquecode', 'standard', 'walmart')
ON DUPLICATE KEY UPDATE code = VALUES(code);
This is better than a WHERE
subquery with EXISTS
because it is thread-safe . 这比具有
EXISTS
的WHERE
子查询更好,因为它是线程安全的 。 That means that multiple updates in different threads will not ever cause a problem. 这意味着不同线程中的多次更新将永远不会造成问题。
This is better than INSERT IGNORE
because INSERT IGNORE
will ignore other errors. 这比
INSERT IGNORE
更好,因为INSERT IGNORE
将忽略其他错误。 ON DUPLICATE KEY UPDATE
does exactly what you want. ON DUPLICATE KEY UPDATE
正是您想要的。
You should first create a UNIQUE INDEX
on the code column. 您应该首先在代码列上创建
UNIQUE INDEX
。 You can then safely insert the data without warnings using: 然后,您可以使用以下命令安全地插入数据而不会发出警告:
INSERT INTO LICENSE_TABLE(code, license_type, distributor)
SELECT 'uniquecode', 'standard', 'walmart'
FROM (SELECT 1) AS x
WHERE NOT EXISTS (
SELECT 1
FROM LICENSE_TABLE
WHERE code = 'uniquecode'
)
Just use INSERT IGNORE
like 只需像这样使用
INSERT IGNORE
INSERT IGNORE INTO LICENSE_TABLE
(code, license_type, distributor)
values ("uniquecode", "standard", "walmart")
But you need to have a unique index on the code
column. 但是您需要在
code
列上具有唯一索引。 Check if you have one already either with show indexes from LICENSE_TABLE;
检查是否已有
show indexes from LICENSE_TABLE;
or show create table LICENSE_TABLE;
或
show create table LICENSE_TABLE;
If you don't have one, you can create one like this: 如果没有,则可以这样创建一个:
create unique index uidx_license_table_code on LICENSE_TABLE(code);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.