php 插入查询检查记录是否存在 - 如果不存在,插入它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15898599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert query check if record exists - If not, Insert it
提问by Sumit Bijvani
I have a mysql table ip_list
...
我有一个 mysql 表ip_list
...
+----+---------------+
| id | ip_addr |
+----+---------------+
| 1 | 192.168.100.1 |
| 2 | 192.168.100.2 |
| 3 | 192.168.100.3 |
| 4 | 192.168.100.4 |
| 5 | 192.168.100.5 |
+----+---------------+
I want to add only that records which are not in ip_addr
column.
For ex
我只想添加不在ip_addr
列中的记录。
前任
I have following records to add in ip_addr
table
我有以下记录要添加到ip_addr
表中
192.168.100.6
192.168.100.10
192.168.100.11
192.168.100.1 //already in column
192.168.100.12
I don't want to add 192.168.100.1
, because it is already in column.
我不想添加192.168.100.1
,因为它已经在列中。
So, is it possible that INSERT
query first check the records then insert it?
那么,INSERT
查询是否有可能首先检查记录然后插入它?
Currently, I am doing this with.. first I SELECT
the records then match it and then INSERT
it.
目前,我正在这样做......首先我SELECT
记录然后匹配它然后INSERT
它。
but, I want to do with only one query.
但是,我只想做一个查询。
回答by Yogesh Suthar
You can use below query. Here it will insert the ip_address when it is not present in your table.
您可以使用以下查询。在这里,当您的表中不存在 ip_address 时,它将插入该地址。
INSERT INTO ip_list (ip_addr)
SELECT * FROM (SELECT '192.168.100.1') AS tmp
WHERE NOT EXISTS (
SELECT ip_addr FROM ip_list WHERE ip_addr='192.168.100.1'
);
回答by mrks
You should add a UNIQUE key on ip_addr
and then use INSERT IGNORE
.
您应该添加一个 UNIQUE 键ip_addr
,然后使用INSERT IGNORE
.
Maybe this helps if you haven't heard of UNIQUE
yet: http://www.tutorialspoint.com/sql/sql-unique.htm
如果您还没有听说过,这可能会有所帮助UNIQUE
:http: //www.tutorialspoint.com/sql/sql-unique.htm
回答by Skinny Pipes
if I were you, I enforce a UNIQUE
constraint on the column,
如果我是你,我会UNIQUE
在列上强制执行约束,
ALTER TABLE ip_list ADD CONSTRAINT IP_Unique UNIQUE(ip_addr)
回答by Suresh Kamrushi
you can do that with Insert...on duplicate key update
你可以用Insert...on 重复键更新来做到这一点
OR
或者
alternatively you can also be use Replace
或者你也可以使用替换
回答by Peter Kiss
Try MySQL INSERT IGNOREstatement.
试试 MySQL INSERT IGNORE语句。