简体   繁体   English

如果已经存在,将不会插入的PHP MySQL插入查询

[英]PHP MySQL Insert Query that won't insert if already exists

I've been doing some research and haven't found anything that I've been able to make work, unfortunately, and I think that stems from not understanding the MySQL construct in the examples I've been looking at. 不幸的是,我一直在做一些研究,没有发现我能做的任何事情,我认为这是由于我一直在看的示例中对MySQL构造的不了解所致。

What I'm trying to do is run an insert query, and do a check on values in 3 specific columns to ensure they don't exist, then insert, else do nothing. 我想做的是运行一个插入查询,并检查3个特定列中的值以确保它们不存在,然后插入,否则什么也不做。

My Table is pretty basic: id(int11), user(varchar(45)), label(varchar(255)), agent(varchar(255)), empid(varchar(10)). 我的表非常基本:id(int11),user(varchar(45)),label(varchar(255)),agent(varchar(255)),empid(varchar(10))。

My id is my Primary, with Auto increment, and here is my code I currently have that works on inserting, but doesn't have the handling in place for duplicates: 我的ID是我的主要用户,具有自动递增功能,这是我目前在插入时可以使用的代码,但是没有处理重复的代码:

$i = 0;
foreach ($agents as $ag){
    $sql = mysql_query("INSERT INTO `pms_users` 
    (`id`,`user`,`label`,`agent`,`empid`)
     VALUES 
    (NULL, '$user','$group','$labels[$i]','$ag')");
    $i ++;
}

The three columns I need to check against are the $user, $group, and $ag. 我需要检查的三列是$ user,$ group和$ ag。

Add a unique index for (user, label, empid) . (user, label, empid)添加唯一索引。 Then the database won't allow you to create duplicates. 然后,数据库将不允许您创建重复项。

ALTER TABLE pms_users
ADD UNIQUE INDEX (user, label, empid);

If you can only have one row per combination of user, label and agent, you should define them as a unique constraint: 如果每个用户,标签和代理的组合只能有一行,则应将它们定义为唯一约束:

ALTER TABLE pms_users ADD CONSTRAINT pms_users_unq UNIQUE (`user`, `label`, `agent`);

And then let the database do the heavy lifting with an insert-ignore statement: 然后让数据库使用insert-ignore语句完成繁重的工作:

INSERT IGNORE INTO `pms_users`
(`user`, `label`, `agent`, `empid`)
VALUES ('some_user', 'some_label', 'some_agent', 123)

You can try insert on duplicate key update query.. It checks duplicate keys. 您可以尝试在重复键更新查询上插入。它检查重复键。 If they exist MySQL do update query if not exist MySQL doing insert query. 如果它们存在,则MySQL执行更新查询;如果不存在,则MySQL执行插入查询。 Sure in your database you should declare unique keys. 确保在数据库中应该声明唯一键。 Here is MySQL documentation for this case https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html 这是此情况的MySQL文档https://dev.mysql.com/doc/refman/8.0/zh-CN/insert-on-duplicate.html

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

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