開始以為和SQL Server一樣,使用not exists進行判斷,結果不行:
IF NOT EXISTS (SELECT 1 FROM vrv_paw_template WHERE templateName='自定義' OR templateFileName='policycustom' LIMIT 1) INSERT INTO vrv_paw_template(templateName,templateFileName,createTime,updateTime) VALUES('自定義','policycustom',NOW(),NOW()); END IF
正確的寫法:
INSERT INTO vrv_paw_template(templateName,templateFileName,createTime,updateTime) SELECT '自定義','policycustom',NOW(),NOW() FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM vrv_paw_template WHERE templateName='自定義' OR templateFileName='policycustom' LIMIT 1 );
注釋:dual 是個臨時表
mysql官方對這個表的解釋吧(http://dev.mysql.com/doc/refman/5.0/en/select.html):
DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.
官方的解釋說:純粹是為了滿足select … from…這一習慣問題,mysql會忽略對該表的引用。
把我發現的三個應用地方都加上:
select express from dual #這條sql就類似上面的查看系統時間一樣。把express替換成表達式或函數就行
select express from dual where condition #這條sql只是對上面的一點擴展 加上一個where條件。其實這個where條件跟我們平時使用的where條件沒什么區別。執行的時候也是先判斷where子句是否成立,滿足然后再執行select中的express,最后返回express執行的值;如果where子句不成立,則返回空。比如:select 1+1 from where 1=1,將返回2。
第三個就是一條比較實用的SQL語句了!你否想過:插入數據時先判斷一下這條 記錄是否已存在這個問題!?也許很多時候為了解決這個問題,你會先select一下,根據他的結果再決定是否繼續寫入數據庫。但是用dual這個表,可以讓你僅一條SQL就可以解決這個問題哦!
SQL就是這樣寫的:
INSERT INTO table (primarykey, field1, field2, ...) SELECT key, value1, value2, ... FROM dual WHERE not exists (select * from table where primarykey = id);
