2016-04-01 90 views
-1

有這樣的說法,我想執行:我如何插入到MySQL與布爾條件

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

但執行之前,我想檢查是否「硝酸鉀」有「5」或沒有。如果沒有,它應該執行。如果它不應該執行。提前致謝。

+0

是'kno'主鍵?或想成爲主鍵? – Sevle

+0

@Sevle沒有它不是PK –

+0

如果數字5是動態的,它必須由編程語言(SQL不)中產生。你不能在這方面的if語句中檢查數字嗎? –

回答

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服務器端。

+0

thanx mate。像魅力一樣工作! –

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/