如何使用布尔条件插入到mysql中

时间:2016-04-01 15:34:02

标签: mysql

我有这个声明,我想执行:

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

但在执行之前我想检查“知道”是否有“5”。如果不是,它应该执行。如果它不应该执行。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以这样做:

    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

答案 1 :(得分:0)

您好我认为可以通过存储过程轻松完成...我建议您阅读本文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/