简体   繁体   English

仅在MySQL表中尚不存在的情况下插入数据:INSERT IGNORE出现问题

[英]Inserting data in MySQL table only if it doesn't exist already: trouble with INSERT IGNORE

so I've been looking around StackOverflow and the MySQL manual for a while, and I can't seem to solve my problem. 因此,我一直在寻找StackOverflow和MySQL手册已有一段时间,但似乎无法解决我的问题。 What I'm trying to do is simply make my data INSERT function such that it doesn't add anything to my table if it already exists. 我想做的就是简单地使我的数据INSERT函数,这样它就不会向我的表添加任何东西(如果已经存在)。 I saw a few methods: the INSERT IGNORE function, together with a unique index, was the one that seemed the best for me, but I have no idea why it is not working... Here is a portion of my code (I have two columns: 'username' and 'email', and my table is called 'info4'): 我看到了一些方法:INSERT IGNORE函数和一个唯一索引对我来说似乎是最合适的,但是我不知道为什么它不起作用...这是我的一部分代码(两列:“用户名”和“电子邮件”,我的表称为“ info4”):

$unique_index = mysqli_query ($con, "CREATE UNIQUE INDEX index ON info4 ( username, email);");

$insert = mysqli_query($con, "INSERT IGNORE INTO info4 (`username`, `email`) VALUES ('$array_values[0]', '$array_values[1]')");

Where am I going wrong? 我要去哪里错了? Am I missing anything? 我有什么想念的吗?

You can't create an index named index. 您无法创建名为index的索引。

Mysql is not case sensitive. Mysql不区分大小写。 Your INDEX wrongly named "index" won't work. 您的INDEX错误地命名为“索引”将不起作用。

Example: 例:

mysql> create index index on tbladresse (strasse_zusatz); mysql>在tbladresse(strasse_zusatz)上创建索引索引; ERROR 1064 (42000): You have an error in your SQL syntax; 错误1064(42000):您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index on tbladresse (strasse_zusatz)' at line 1 检查与您的MySQL服务器版本对应的手册以获取正确的语法,以在第1行的“ tbladresse上的索引(strasse_zusatz)”附近使用

mysql> create index iindex on tbladresse (strasse_zusatz); mysql>在tbladresse(strasse_zusatz)上创建索引iindex; Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0 查询正常,受影响的0行(0.03秒)记录:0重复:0警告:0

Insert Ignore simply tells MySQL to not issue a duplicate key error when trying to insert duplicate data into fields with unique constraints. 尝试将重复数据插入具有唯一约束的字段时,“ Insert Ignore只是告诉MySQL不要发出重复键错误。

The unique index should be all you need to stop duplicate entries from being inserted. 唯一索引应该是阻止插入重复项所需的全部。

Generally you wouldn't want to do things like add indexes using PHP, you should do that via whatever tool you are using to access your database. 通常,您不想使用PHP添加索引之类的东西,您应该通过用于访问数据库的任何工具来做到这一点。

Are you seeing duplicate username/email combos being inserted into your table? 您是否看到表中插入了重复的用户名/电子邮件组合? What are the values of $array_values[0] and $array_values[1] ? $array_values[0]$array_values[1]的值是什么?

If you do SHOW INDEX FROM info4 do you see your unique index? 如果您SHOW INDEX FROM info4 ,您会看到自己的唯一索引吗?

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

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