Mysql資料庫If語句的使用

2022-09-08 04:54:09 字數 2797 閱讀 5099

mysql 的if既可以作為表示式用,也可在儲存過程中作為流程控制語句使用,如下是做為表示式使用:

if表示式

if(expr1,expr2,expr3)

如果 expr1 是true (expr1 <> 0 and expr1 <> null),則 if()的返回值為expr2; 否則返回值則為 expr3。if() 的返回值為數字值或字串值,具體情況視其所在語境而定。

select

if(sva=

1,"男","女") as ssva from taname where id =

'111

'

作為表示式的if也可以用case when來實現:

select

case sva when

1then'男

'else'女

'end

as ssva from taname where id ='1

'

在第乙個方案的返回結果中, value=compare-value。而第二個方案的返回結果是第一種情況的真實結果。如果沒有匹配的結果值,則返回結果為else後的結果,如果沒有else 部分,則返回值為 null。

select

case

1when

1then

'one

'when

2then

'two

'else

'more

'end

as testcol

將輸出one

ifnull(expr1,expr2)

假如expr1 不為 null,則 ifnull() 的返回值為 expr1; 否則其返回值為 expr2。ifnull()的返回值是數字或是字串,具體情況取決於其所使用的語境。

mysql>

select ifnull(1,0

);  

->

1mysql

>

select ifnull(null,10

);  

->

10mysql

>

select ifnull(1

/0,10

);  

->

10mysql

>

select ifnull(1

/0,'

yes'

);  

->

'yes

'

fnull(expr1,expr2) 的預設結果值為兩個表示式中更加「通用」的乙個,順序為string、 real或 integer。

if else 做為流程控制語句使用

if實現條件判斷,滿足不同條件執行不同的操作,這個我們只要學程式設計的都知道if的作用了,下面我們來看看mysql 儲存過程中的if是如何使用的吧。

if search_condition then

statement_list    

[elseif search_condition then

]statement_list ...    

[else   

statement_list

]end

if

與php中的if語句類似,當if中條件search_condition成立時,執行then後的statement_list語句,否則判斷elseif中的條件,成立則執行其後的statement_list語句,否則繼續判斷其他分支。當所有分支的條件均不成立時,執行else分支。search_condition是乙個條件表示式,可以由「=、<、<=、>、>=、!=」等條件運算子組成,並且可以使用and、or、not對多個表示式進行組合。

select

*, (

select

count( distinct

money

) from (select g.operator, floor( ifnull( sum( g.visitmoney ) , 0 ) ) `money` , count( *

) num, u.username

from `guest` g, user

uwhere g.operator =

u.id

and u.group=2

and g.isvisittime >

1543766400

and g.isvisittime <

1544371200

group

byoperator

order

by `money` desc

)aawhere

money

>= a.money

) as

row

from

(select g.operator, floor( ifnull( sum( g.visitmoney ) , 0 ) ) `money` , count( *

) num, u.username

from `guest` g, user

uwhere g.operator =

u.id

and u.group=2

and g.isvisittime >

1543766400

and g.isvisittime <

1544371200

group

byoperator

order

by `money` desc

)a

Mysql資料庫If語句的使用

mysql的if既可以作為表示式用,也可在儲存過程中作為流程控制語句使用,如下是做為表示式使用 if表示式 sql view plain copy if expr1,expr2,expr3 如果 expr1 是true expr1 0 and expr1 null 則 if 的返回值為expr2 否...

MySQL資料庫使用相關語句

編碼格式 配置檔案 修改資料庫外網許可權 索引 usr bin 客戶端程式和指令碼 usr sbin mysqld 伺服器 var lib mysql 日誌檔案,資料庫 重點要知道這個 usr share doc packages 文件 usr include mysql 包含 頭 檔案 usr l...

mysql資料庫索引語句 MySQL資料庫之索引

一 什麼是索引 索引是一種用於快速查詢到匹配條件的資料的資料結構,是用來加快查詢的技術。索引對良好的資料庫效能來說,是乙個非常重要的指標。當表中的資料量越來越大的時,其索引就越來越重要。基本法則 索引應該構建在被用作 查詢條件 的字段上 索引型別 1 b tree索引 btree樹的特性 多路平衡樹...