MySQL if判断语句以及条件查询语句


一、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; 

3、查询当前表最新一条数据

     select * from t__msg order by id DESC limit 1   


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM