mysql条件更新或者insert_有条件的mySQL语句。如果为真UPDATE,如果为假INSERT

bd96500e110b49cbb3cd949968f18be7.png

I'm trying to create more robust MySQL Queries and learn in the process. Currently I'm having a hard time trying to grasp the ON DUPLICATE KEY syntax and possible uses.

I have an INSERT Query that I want to INSERT only if there is no record with the same ID and name, otherwise UPDATE. ID and name are not UNIQUE but ID is indexed.ID isn't UNIQUE because it references another record from another table and I want to have multiple records in this table that reference that one specific record from the other table.

How can I use ON DUPLICATE KEY to INSERT only if there is no record with that ID and name already set else UPDATE that record?

I can easily achieve this with a couple of QUERIES and then have PHP do the IF ELSE part, but I want to know how to LIMIT the amount of QUERIES I send to MySQL.

解决方案

UPDATE: Note you need to use IF EXISTS instead of IS NULL as indicated in the original answer.

Code to create stored procedure to encapsulate all logic and check if Flavours exist:

DELIMITER //

DROP PROCEDURE `GetFlavour`//

CREATE PROCEDURE `GetFlavour`(`FlavourID` INT, `FlavourName` VARCHAR(20))

BEGIN

IF EXISTS (SELECT * FROM Flavours WHERE ID = FlavourID) THEN

UPDATE Flavours SET ID = FlavourID;

ELSE

INSERT INTO Flavours (ID, Name) VALUES (FlavourID, FlavourName);

END IF;

END //

DELIMITER ;

ORIGINAL:

You could use this code. It will check for the existence of a particular record, and if the recordset is NULL, then it will go through and insert the new record for you.

IF (SELECT * FROM `TableName` WHERE `ID` = 2342 AND `Name` = 'abc') IS NULL THEN

INSERT INTO `TableName` (`ID`, `Name`) VALUES ('2342', 'abc');

ELSE UPDATE `TableName` SET `Name` = 'xyz' WHERE `ID` = '2342';

END IF;

I'm a little rusty on my MySQL syntax, but that code should at least get you most of the way there, rather than using ON DUPLICATE KEY.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值