【问题标题】:Is there an easy way to INSERT an row when not exists? otherwise give an error using a single MySql query?有没有一种简单的方法可以在不存在时插入一行?否则使用单个 MySql 查询会出错?
【发布时间】:2013-07-29 07:00:24
【问题描述】:

我将用户的详细信息插入数据库,我的要求是仅插入用户的记录,如果它不存在。如果 namepostcode 已经存在,则提示用户 "record already exist with the same name or post code"

这里是插入查询 "INSERT INTO sender_list (sender_serial_number , sender_name ,sender_address_id) VALUES ('$sender_serial_number' , '$sender_name' , '$sender_post_code')"

【问题讨论】:

  • 添加UNIQUE约束。
  • 名称的唯一键?它是一个文本
  • 您不想在文本列上创建唯一索引,因为...?
  • 我在 ID 字段中已经有一个唯一的。如果我想让发件人名称唯一,它给出的错误为#1062 - Duplicate entry 'fdas' for key 'name'
  • 在其他列上已有唯一索引是个问题,因为...?

标签: mysql


【解决方案1】:

在表上添加UNIQUE 约束后,在INSERT 操作后检查PHP 中的mysql_errno()。 if(mysql_errno() !== 0) 则该记录已存在,出现错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-07
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2012-12-03
    相关资源
    最近更新 更多