MySQL 的if条件判断和where相关条件查询

MySQL 的if条件判断和where相关条件查询

一、sql 中if条件的使用

如:查询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 对行去重,查询唯一的一行数据,对重复行去重。

二、sql 中 “ where 1=1 ” 和 “ where 1<>1 ”的使用

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;


版权声明:本文为qq_43170312原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。