Mysql中的小技巧

1.where 字段名 regexp '正则表达式'

正则符号: ^ $ . [ ] * |
  . 表示1个任意字符
  * 表示前面重复0次,或者任意次
  ^ 开始
  $ 结尾
  [] 范围
  | 或                         

sql示例:

#查询以【李】开头的
select name from user where name regexp '^李';
#查询以【小】结尾的
select name from user where name regexp '小$';
#查询以【李】开头,中间任意,结尾以【四】的
select name from user where name regexp '^李.*四$';
#查询名字以【李】开头,或者以【小】结尾的
select name from user where name regexp '^李|小$';

2. instr、concat搜索和连接字符串

数据字段中存放的是id集,形如  1,2,15,35 也可类推json格式
查询时不用拆分了, 用上 instr、concat搜索和连接字符串
查询ids中包含15的

sql示例:
select * from [table-表名] where instr(concat(',', ids, ','), ',15,') > 0

3.查询时,多个字段 like 同个值

like多个值 and和的关系
like多个值 or的关系  可用regexp

sql示例:
select * from user where name regexp '张三|李四'

4.查询结果过滤

having用法:
SQL查询 having 条件表达式;就是在查询结果中再查询一次

sql示例:
select name from user where name !="李四" having name="李小小";

5.mysql内置对数据进行统计的指令

聚焦函数:
  avg(字段名)
  sum(字段名)
  min(字段名)
  max(字段名)
  count(字段名)

sql示例:

##查询名字不等于李四的人员的平均分数
select avg(score) from user where name != "李四";
##查询最高分数
select max(score) from user;
##查询最低分数
select min(score) from user;
##查询总分数
select sum(score) from user;
##统计user表中的行数
select count(*) from user;

6.mybatis中mapper.xml where下foreach写法

A写法:

<where>
  ID in
   <foreach close=")" collection="array" item="ids" open="(" separator=",">
      '${ids}'
    </foreach>
</where>

B写法:

<where>
  <if test="ids!= null and ids.size() > 0">
        and id in
        <foreach collection="ids" item="item" index="index" open="(" separator="," close=")">
            #{item}
        </foreach>
  </if>​
<where>

6.批量删除的写法

mybatis中mapper.xml

 <delete id="deleteByIds">
        delete from notice_announcement
        <where>
            ID in
            <foreach close=")" collection="array" item="ids" open="(" separator=",">
                '${ids}'
            </foreach>
        </where>
    </delete>

mapper接口

 int deleteByIds(String[] ids);
posted @ 2021-12-19 13:54  奋--斗  阅读(117)  评论(0编辑  收藏  举报