insert語句讓我學會的兩個MySQL函式

2022-08-09 10:54:12 字數 2168 閱讀 2598

我們要儲存資料到資料庫,插入資料是必須的,但是在業務中可能會出於某種業務要求,要在資料庫中設計唯一索引;這時如果不小心插入一條業務上已經存在同樣key的資料時,就會出現異常。

大部分的需求要求我們出現唯一鍵衝突時就更新這條資料,這時我們就可以用下面這條mysql語句了:

insert

[low_priority | delayed | high_priority][

ignore][

into

]tbl_name

[partition (partition_name [, partition_name

]...)]

[(col_name [, col_name

]...)]

(value_list) [

, (value_list)

]...

[on duplicate key update assignment_list

]

這個就是mysql官方的insert ... on duplicate key update語句語法

對於上面的 assignment_list 我們常常這樣寫:(假設a所在列是資料庫中的唯一主鍵)

insert

into t1 (a,b,c) values (1,2,3),(4,5,6)

on duplicate key

updateb=

b, c

=c;

但是在業務上,對於b和c列的值並不是所有的數值都是需要更新到資料庫裡的,比如說:b列不能為null,為空就不更,c列不能小於0,小於0時就不更新,那麼上面的語句我們就必須改改了:

insert

into t1 (a,b,c) values (1,2,3),(4,5,6)

on duplicate key

updateb=

if(values(b), values

(b), b),

c=if(values(c) >

0, values(c), c);

我這次要說的就是這兩個函式if和values

下面就看官網怎麼說了:

in aninsert ... on duplicate key updatestatement, you can use thevalues(col_name) function in theupdateclause to refer to column values from theinsertportion of the statement. in other words,values(col_name) in theupdateclause refers to the value ofcol_namethat would be inserted, had no duplicate-key conflict occurred. this function is especially useful in multiple-row inserts. thevalues()function is meaningful only in theon duplicate key updateclause ofinsertstatements and returnsnull

ifexpr1istrue(expr1<> 0 andexpr1<> null),if()returnsexpr2. otherwise, it returnsexpr3.

對於if函式來說,就是根據條件二選一了,沒啥可說的,

對於values函式來說,只有在on duplicate key update語句裡才有意義,而且返回值,是你要插入的數值,而不是已經在資料庫裡的數值。

隨便發現了南洋理工的sql教程,很讚:

insert語法

if函式

values函式

兩個小時學會DirectDraw程式設計

這並非譁眾取寵,通常學習一種電腦技術有兩種方法.一種是自己摸索,在錯誤的方向上一錯再錯,屢戰屢敗,不過最後得道成功.另一種是有人 或好的材料指導,因而事半功倍,在正確的方向上走了速成的捷徑.就象kfc 的雞一樣.第一種學法能學出電腦天才,因為所謂電腦高手,其實就是排錯試錯的高手.而第二種則出電腦專才...

組合兩個表 sql查詢語句

表1 person 列名 型別 personid int firstname varchar lastname varchar personid 是上表主鍵表2 address 列名 型別 addressid int personid int city varchar state varchar a...

兩個sql交集 SQL語句的多表查詢

1.練習如何合併連個表,注意使用union all語句表示保留重複項 2.內聯結 在from子句中同時使用了兩張表,並對每張表起了別名a和b,student as a 在列名中用 a.列名 表示某一句 from子句中用inner join表達內聯結,選取出同時存在於兩張表中的資料 on子句中表達兩個...