【问题标题】:IGNORE not working Mysql忽略不工作的Mysql
【发布时间】:2013-03-15 20:06:24
【问题描述】:

您好,我正在通过脚本导入 csv 表结构如下

`contact_id` int(11) NOT NULL auto_increment,
  `contact_first` varchar(255) character set latin1 default NULL,
  `contact_last` varchar(255) character set latin1 default NULL,
  `contact_email` varchar(255) character set latin1 default NULL,
  PRIMARY KEY  (`contact_id`)

而csv中的数据是这样的

Jim,Smith,jim@tester.com
Joe,Tester,joe@tester.com

我用于插入的查询如下

mysql_query("INSERT IGNORE INTO contacts (contact_first, contact_last, contact_email) VALUES
                (
                    '".addslashes($data[0])."',
                    '".addslashes($data[1])."',
                    '".addslashes($data[2])."'
                )
            ");

我在查询中使用了忽略功能,但它不起作用,它继续插入相同的值

【问题讨论】:

    标签: php mysql insert


    【解决方案1】:

    IGNORE 关键字只会对重复行产生您想要的影响。

    只有在相应列上有主键或唯一键时,才会将行识别为重复。

    您还没有真正解释到底是什么问题,但我怀疑您可能希望在 contact_email 列上创建一个唯一键以防止插入重复项。

    我还建议至少使用mysql_escape_string 而不是addslashes 以确保正确编码字符串。

    可能会有关于 mysql_* 函数已弃用的事实,因此您应该查看 PDO 或 mysqli_* 函数。

    【讨论】:

      【解决方案2】:

      如果您使用 IGNORE 关键字,则执行 INSERT 语句时发生的错误将被视为警告 参考DOCS

      【讨论】:

        【解决方案3】:

        IGNORE的用法是:

        If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.

        在您的情况下,您要插入三个相同的值,但 ID 是 auto incremental,这将插入具有相同值的新记录,这是显而易见的。 如果你想阻止它插入到数据库中,你必须将唯一索引添加到另一列中

        希望它会有所帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-19
          • 1970-01-01
          • 1970-01-01
          • 2020-12-04
          • 2019-03-22
          相关资源
          最近更新 更多