如何用布尔条件插入mysql

3phpmpom  于 2023-04-28  发布在  Mysql
关注(0)|答案(2)|浏览(134)

我想执行以下语句:

INSERT INTO kitchenitems (kno, `date`, added_Date, added_By) 
VALUES (5,'2016-04-01', now(), 2);

但在执行之前,我想检查“kno”是否有“5”。如果没有,它应该执行。如果有,则不应执行。先谢谢你了。

up9lanfz

up9lanfz1#

你可以这样做:

INSERT INTO kitchenitems (`kno`, `date`, `added_Date`,`added_By`)
    SELECT kno,date,added_Date,added_By
    FROM (SELECT '5' as kno, '2016-04-01' as date, NOW() as added_Date, '2' as added_By) a
    WHERE NOT EXISTS (SELECT 1 FROM kitchenitems b WHERE a.kno = b.kno);

但是,如果您想要kno的唯一值,您应该在服务器端使用ensure that

uidvcgyl

uidvcgyl2#

我认为这可以很容易地用存储过程来完成。..我建议你阅读这篇文章HERE我认为这是你的解决方案的答案。
下面是SQL Fiddle,看看它是如何解决你的问题的。..
以下是存储过程

CREATE PROCEDURE addItem 
(IN inkno INT, IN inddate DATETIME, IN inadded_Date DATETIME, IN inadded_By INT)
BEGIN
    DECLARE SomeId int;
    DECLARE CheckExists int;  
    SET CheckExists = 0;  

    SELECT count(*) INTO CheckExists from kitchenitems WHERE kno = inkno;   

    IF (CheckExists > 0) THEN 
        SELECT kno INTO SomeId FROM kitchenitems WHERE kno = inkno;  
    ELSE 
        INSERT INTO kitchenitems (kno,ddate,added_Date,added_By) 
        VALUES (inkno, inddate,inadded_Date, inadded_By); 
    END IF;

END/

相关问题