mysql判斷表記錄是否存在,不存在則插入新紀錄

來源:互聯網
上載者:User

標籤:

開始以為和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);

mysql判斷表記錄是否存在,不存在則插入新紀錄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.