SQL IF EXISTS覆盖错误

时间:2013-10-25 19:36:17

标签: php sql sql-update exists sql-insert

我正在尝试建立一个系统来检查它是否存在,如果确实存在则覆盖,如果没有则插入。我在这段代码中有一个错误,但在我的生活中我看不到它。我尝试过两种不同的方法,但都没有。

mysqli_query($con,"IF (SELECT COUNT(*) FROM saves
WHERE name='$_POST[name]') > 0
BEGIN
    UPDATE saves SET entity='$_POST[saveEntity]' WHERE name='$_POST[name]'
END
ELSE
BEGIN
    INSERT INTO saves (`name`, `ID`, `entity`)
    VALUES ('$_POST[name]', NULL, '$_POST[saveEntity]')
END");

OR

mysqli_query($con,"IF EXISTS(SELECT * FROM saves WHERE name='$_POST[name]')
BEGIN
    UPDATE saves SET entity='$_POST[saveEntity]' WHERE name='$_POST[name]'
END
ELSE
BEGIN
    INSERT INTO saves (`name`, `ID`, `entity`)
    VALUES ('$_POST[name]', NULL, '$_POST[saveEntity]')
END");

2 个答案:

答案 0 :(得分:1)

您应该在“name”列上设置主键,然后使用如下语法:

  

INSERT INTO保存(column1,column2,column3,...)VALUES(1,2,3,...)
  ON DUPLICATE KEY UPDATE entity ='your value';

答案 1 :(得分:0)

试试这个,否则你可能需要调整+'“和'”+ i

mysqli_query($con,"IF EXISTS(SELECT * FROM saves WHERE name='"+$_POST[name]+"')
BEGIN
    UPDATE saves SET entity='"
+ $_POST[saveEntity]+ "'  WHERE name='"+$_POST[name]+"'
END
ELSE
BEGIN
    INSERT INTO saves (`name`, `ID`, `entity`)
    VALUES ('"+$_POST[name]+"', NULL, '"+$_POST[saveEntity]+"')
END");

但对于sql我只会插入不存在的地方 然后直到约会,我不知道这是我的想法

mysqli_query($con,"
INSERT INTO saves (`name`, `ID`, `entity`)
    VALUES ('"+$_POST[name]+"', NULL, '"+$_POST[saveEntity]+"')
where name not in 
(SELECT name FROM saves WHERE name)

go 
    UPDATE saves SET entity='"
+ $_POST[saveEntity]+ "'  WHERE name='"+$_POST[name]+"'");