SQL - IF EXISTS UPDATE ELSE INSERT INTO

时间:2013-03-13 11:21:05

标签: mysql sql insert exists

我尝试做的是我的数据库中的INSERT个订阅者,但是IF EXISTS它应该UPDATE行,ELSE INSERT INTO一个新行。

当然,我首先连接到数据库,然后从网址字符串GET$name$email$birthday连接到数据库。

$con=mysqli_connect("localhost","---","---","---");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$name=$_GET['name']; 
$email=$_GET['email'];
$birthday=$_GET['birthday'];

这样可行,但只需添加新行;

mysqli_query($con,"INSERT INTO subs (subs_name, subs_email, subs_birthday)
VALUES ('$name', '$email', '$birthday')");

mysqli_close($con);

这是我尝试的内容;

mysqli_query($con,"INSERT INTO subs (subs_name, subs_email, subs_birthday)
VALUES '$name', '$email', '$birthday'
ON DUPLICATE KEY UPDATE subs_name = VALUES($name), subs_birthday = VALUES($birthday)");
mysqli_close($con);

mysqli_query($con,"IF EXISTS (SELECT * FROM subs WHERE subs_email='$email')
    UPDATE subs SET subs_name='$name', subs_birthday='$birthday' WHERE subs_email='$email'
ELSE
    INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES ('$name', '$email', '$birthday')");
mysqli_close($con);

mysqli_query($con,"IF NOT EXISTS(SELECT * FROM subs WHERE subs_email='$email')
Begin
INSERT INTO subs (subs_name, subs_email, subs_birthday)
VALUES ('$name', '$email', '$birthday')
End");
mysqli_close($con);

但它们都不起作用,我做错了什么?

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:181)

  1. subs_email列上创建UNIQUE constraint,如果尚不存在:

    ALTER TABLE subs ADD UNIQUE (subs_email)
    
  2. 使用INSERT ... ON DUPLICATE KEY UPDATE

    INSERT INTO subs
      (subs_name, subs_email, subs_birthday)
    VALUES
      (?, ?, ?)
    ON DUPLICATE KEY UPDATE
      subs_name     = VALUES(subs_name),
      subs_birthday = VALUES(subs_birthday)
    
  3.   

    您可以使用UPDATE子句中的VALUES(col_name)函数   引用INSERT ... ON的INSERT部分的列值   DUPLICATE KEY UPDATE - dev.mysql.com

    1. 请注意,我在字符串文字的位置使用了参数占位符,因为一个真的应该使用参数化语句defend against SQL injection attacks

答案 1 :(得分:-2)

尝试一下:

INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';