MySQL 的if條件判斷和where相關條件查詢

2021-10-11 19:14:30 字數 815 閱讀 4083

如:查詢t_role角色表中是否存在t_user使用者表中joi使用者的資訊

select distinctrow * from t_user u left join t_role r on r.uid = u.uid and r.state = 1 where if (r.uid is not null , r.name = 『joi』 , 1 <> 1)

這裡if的用法和三目運算類似,如果「r.uid is not null」條件滿足,說明role表中存在uid相等的使用者,然後選中「r.name = 『joi』」條件,就會從左連線的結果中去查詢滿足「 r.name = 『joi』 」的資訊;否則會選中」 1 <> 1 「條件(1 <> 1為永假條件)。distinctrow 對行去重,查詢唯一的一行資料,對重複行去重。

1、「 where 1=1 」通常用於動態sql,方便在拼接sql的時候直接拼「 and 『條件1』 」,不用判斷是否是第乙個查詢條件而處理要不要加「 and 」的兩種情況。

2、「 where 1<>1 」用於只取結構不取資料的場合。

如:create table user_copy tablespace user_copy as select * from user where 1<>1

建成乙個和user表結構完全相同的uer_copy表 ,但不拷貝user表中的資料。

另:拷貝表

create table_name as select * from source_table where 1=1;

複製表結構

create table_name as select * from source_table where 1 <> 1;

Shell指令碼IF條件判斷和判斷條件總結

前言 無論什麼程式語言都離不開條件判斷。shell也不例外。如下 if list then do something here elif list then do another thing here else do something else here fiex1 bin sh system u...

Shell指令碼IF條件判斷和判斷條件總結

自 前言 無論什麼程式語言都離不開條件判斷。shell也不例外。if list then dosomething here elif list then doanother thing here else dosomething else here fi ex1 bin sh system unam...

Shell指令碼IF條件判斷和判斷條件總結

前言 無論什麼程式語言都離不開條件判斷。shell也不例外。if list then do something here elif list then do another thing here else do something else here fi ex1 bin sh system una...