Home > database >  MYSQL before inserting data, judge whether there is any, is inserted, what is wrong
MYSQL before inserting data, judge whether there is any, is inserted, what is wrong

Time:09-27

If not the exists (SELECT * FROM Site_About WHERE ID=2), then the
Insert into Site_About (ID, PropertyType, Title, Body, SortIndex) values (2, '1', '222', '222', 1)
The else
The update Site_About set PropertyType='1', the Title='222', the Body='222', SortIndex=1 where ID=2
End the if


There is an error in this statement

CodePudding user response:

You the meaning of this statement is that there is no record of id=2 insert record, update records exist, what mistakes do the report?

CodePudding user response:

Feel the best is to write a stored procedure, you should be a semicolon,
 DELIMITER $$

DROP PROCEDURE IF the EXISTS ` : QQQ ` $$

CREATE PROCEDURE ` : QQQ ` ()
The BEGIN
If not the exists (SELECT * FROM aaa WHERE ID=37) then
Insert into aaa (id, val1) values (37, '1');
The else
The update aaa set val1='1' where ID=37;
end if;
END $$

DELIMITER ;

CodePudding user response:

Suggest you still use the replace into is inserted into a downside is that there is no delete this primary key ID will increase sharply

CodePudding user response:

Set the ID primary key, or set up the only index
And then you can use the REPLACE directly INTO or INSERT INTO ON DUPLICATE the UPDATE

CodePudding user response:

The REPLACE INTO direct solution, there is update, no insert, comfortable!
  • Related