简体   繁体   English

如果不存在,将条目添加到数据库的最快方法

[英]Fastest way to add entry to DB if not exists

I want to add set of entries to MySQL DB table. 我想将一组条目添加到MySQL DB表中。 I need to add entry if it doesn't exist, and otherwise send some signal outside that it wasn't added (fe return false). 我需要添加条目(如果它不存在),否则会向外部发送一些未添加的信号(fe return false)。

I can check if entry exists (with one query) and add it if not exists with another. 我可以检查条目是否存在(使用一个查询),如果不存在则添加它。 However, cause there may be thousands of entries I need to add, I think that extra query is not good. 但是,由于可能需要添加数千个条目,因此我认为额外的查询不是很好。

Can I somehow use just one MySQL query, that would add entry if it doesn't exist and return false if it exists? 我可以以某种方式只使用一个MySQL查询吗?如果不存在,它将添加条目,如果存在,则返回false?

You could use WHERE NOT EXIST syntax: 您可以使用WHERE NOT EXIST语法:

INSERT INTO table (name, address, tele)
VALUES ('John', 'Somewhere', '001')
WHERE NOT EXISTS (
    SELECT name FROM table WHERE name='value'
);

To optimize query using WHERE NOT/EXIST queries with insert, you can do it like this: 要使用带有插入的WHERE NOT / EXIST查询来优化查询,您可以这样做:

INSERT INTO table (name, address, tele)
VALUES ('John', 'Somewhere', '001')
WHERE NOT EXISTS (
    SELECT 1 FROM table WHERE name='value'
);

Which can be further optimize using LIMIT 1 like: 可以使用LIMIT 1进一步优化,例如:

INSERT INTO table (name, address, tele)
VALUES ('John', 'Somewhere', '001')
WHERE NOT EXISTS (
    SELECT 1 FROM table WHERE name='value' LIMIT 1
);

Note: SELECT 1 is faster that SELECT [column_name]... 注意: SELECT 1SELECT [column_name]...更快SELECT [column_name]...

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

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