mysql

1 每个语句的结束记得加分号;

2where条件里再做if分支
    SELECT *FROM `table` WHERE IF( `parentID` is null, `plan_id` <10, `plan_id` >500 )
  还可以再嵌套使用
  WHERE IF(device_id is null , IF(globle_name IS NULL OR globle_name = '', 1 = 1, (P.FileName like concat('%', globle_name, '%') OR D.Name like concat('%', globle_name, '%') OR E.Name like concat('%', globle_name, '%'))), D.id = device_id and P.IsPublished = 1)

3 is null, is not null 用于判断某个字段或是变量为null或不为null.

4 isnull(expr) 的用法:
  如expr 为null,那么isnull() 的返回值为 1,否则返回值为 0。

5 ifnull(exp1,exp2)如果exp1是null的话,就用exp2的值,否则还是用exp1的值

6 NULLIF(expr1,expr2)    如果expr1 =   expr2     成立,那么返回值为NULL,否则返回值为   expr1

7 out参数,存储过程的参数要指明in,out。在调用存储过程时,用带@开头的变量来接收out的值,比如 call procedure1(1,1,@result);

8 用户自定义变量不用声明,直接在变量前加@就可用

9 select count(distinct id) as rowCount from table1,sql server 同样可行。

10 Mysql数据库里表名大小写敏感,字段名大小写不敏感,所以写表名或表的别名时一定要注意大小写。sql server里大小写不敏感

11 FIND_IN_SET(str,strlist)。 strlist为一个用逗号隔开N个字符组成的字符串,返回值的范围在 0 到 N 之间。匹配到值的话,就返回该值的位置,匹配不到返回0。不走索引。

12 in函数, wher id in (1,2,3);如果查询的字段为主键的话,会走索引查询,效果比find_in_set高很多。

EXPLAIN select * from Device where find_in_set(id, '1,2,3,null');  range为all,
EXPLAIN select * from Device WHERE ID IN(1,2);  range为const ,而且还是走的聚集索引查找

13 用union all代替union, union 会过滤掉重复的数据。如果知道数据不会重复,或不在乎是否重复,请使用UNION ALL

14  一些特殊的表名和字段名,在使用时需要加上反单引号··,比如SELECT * FROM `Procedure`; 这个符号是和波浪线~同一个键盘的

15   select utc_timestamp()取到UTC的时间,select now()取数据库所在服务器的时间

插入数据后返回自增ID的方法:

declare newID int(15); //这种变量声明在存储过程里使用

insert into `Table1` (Field1,Field2) values (1,2) ;

select @@IDENTITY INTO newID;  //还有很多其他的方式取,不一一列举

用逗号分隔的数值做存储过程的参数来实现查询功能

CREATE DEFINER=`admin`@`%` PROCEDURE `SP_CREATE_PERSON_TO_GROUP`( in groupIdsWithComma VARCHAR(1000), in userId INT(15))
BEGIN
DECLARE new_id INT(15);
insert into `person` (UserId) values (userId) ;
-- 取得最新的自增值
SELECT @@IDENTITY INTO new_id ; //将查询的结果直接添加到表中
insert into personGroup(PersonId,GrouopId)
select new_id , GroupID from Group where id in(deviceIdsWithComma); END

调用存储过程:

call SP_CREATE_PERSON_TO_GROUP('1,3',1);

varchar和char的区别

char是固定长度的,用于存储固定长度的数据;

varchar会根据具体的长度来使用存储空间,另外varchar需要用额外的1-2个字节存储字符串长度。
  1). 当字符串长度小于255时,用额外的1个字节来记录长度
  2). 当字符串长度大于255时,用额外的2个字节来记录长度
  比如char(255)和varchar(255),在存储字符串"hello world"时,char会用一块255个字节的空间放那个11个字符;它先计算字符串长度为11,然后再加上一个记录字符串长度的字节,一共用12个字节存储,这样varchar在存储不确定长度的字符串时会大大减少存储空间。

varchar和nvarchar的区别
1. varchar(n):长度为n个字节的可变长度且非Unicode的字符数据。n必须是一个介于1和8,000之间的数值。存储大小为输入数据的字节的实际长度

2. nvarchar(n):包含n个字符的可变长度Unicode字符数据。n的值必须介于1与4,000之间。字节的存储大小是所输入字符个数的两倍。所输入的数据字符长度可以为零

 将查询结果放到变量里

SELECT
c1, c2, c3, ...
INTO
@v1, @v2, @v3,...
FROM
table_name
WHERE
condition;
select @v1;

  这里的变量不用declare来声明,直接拿来用。变量的数量必须和查询的列数一致,而且只能用在查询结果是0行或1行的情况下。

The number of variables must be the same as the number of columns or expressions in the select list. In addition, the query must returns zero or one row.

myBatis

动态构建sql语句

if

<if test="state != null">
state = #{state}
</if>

  

choose when otherwise,不想写太多条件语句的时候,可以用这个

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>

  

where, 会自动去掉多余的and 或or

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
and state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>

  

trim ,显示的去掉字符

<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>

set,会自动去掉多余的逗号

<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio},</if>
</set>
where id=#{id}
</update>

  

foreach, 多用于查询语句, 很好用,collection是传入的集合类型的变量名

<select id="findTest" resultType="com.map.expample.entity.Test">
  select * from Tests
  <where>
    id in
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
    </foreach>
  </where>
</select>

bind

<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>

  

mybatis里所有的判断都是用test  ="",比如test="username != null"

mybatis调用存储过程

 <!-- 创建多个文档 -->
<select id="createProcedures" parameterType="map" >
<foreach collection="entities" item="entity" index="index" >
call SP_CREATE_PROCEDURE(
#{entity.fileName, mode=IN, jdbcType=VARCHAR},
#{entity.filePath, mode=IN, jdbcType=VARCHAR},
#{entity.deviceIdsWithComma, mode=IN, jdbcType=VARCHAR},
#{entity.createUserId, mode=IN, jdbcType=VARCHAR}
);
</foreach>
</select>

 

mybatis语法,从数据库查出来的字段可以多于或少于resultType指定的类的属性,都会按能对应的上的名字进行映射。

myBatis JDBC type和java数据类型对应表:

resulstMap 的使用

<resultMap id="detailedBlogResultMap" type="Blog">
<constructor>
<idArg column="blog_id" javaType="int"/>
</constructor>
<result property="title" column="blog_title"/>
<association property="author" javaType="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/>
<result property="bio" column="author_bio"/>
<result property="favouriteSection" column="author_favourite_section"/>
</association>
<collection property="posts" ofType="Post">
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
<association property="author" javaType="Author"/>
<collection property="comments" ofType="Comment">
<id property="id" column="comment_id"/>
</collection>
<collection property="tags" ofType="Tag" >
<id property="id" column="tag_id"/>
</collection>
<discriminator javaType="int" column="draft">
<case value="1" resultType="DraftPost"/>
</discriminator>
</collection>
</resultMap>
<select id="selectBlogDetails" parameterType="int" resultMap="detailedBlogResultMap">
select
B.id as blog_id,
B.title as blog_title,
B.author_id as blog_author_id,
A.id as author_id,
A.username as author_username,
A.password as author_password,
A.email as author_email,
A.bio as author_bio,
A.favourite_section as author_favourite_section,
P.id as post_id,
P.blog_id as post_blog_id,
P.author_id as post_author_id,
P.created_on as post_created_on,
P.section as post_section,
P.subject as post_subject,
P.draft as draft,
P.body as post_body,
C.id as comment_id,
C.post_id as comment_post_id,
C.name as comment_name,
C.comment as comment_text,
T.id as tag_id,
T.name as tag_name
from Blog B
left outer join Author A on B.author_id = A.id
left outer join Post P on B.id = P.blog_id
left outer join Comment C on P.id = C.post_id
left outer join Post_Tag PT on PT.post_id = P.id
left outer join Tag T on PT.tag_id = T.id
where B.id = #{id}
</select>
  

refer:https://www.jianshu.com/p/75493a342f63

MYSQL mybatis的更多相关文章

  1. mysql+mybatis递归调用

    递归调用的应用场景常常出现在多级嵌套的情况,比如树形的菜单.下面通过一个简单的例子来实现mysql+mybatis的递归. 数据模型 private Integer categoryId; priva ...

  2. Java Spring+Mysql+Mybatis 实现用户登录注册功能

    前言: 最近在学习Java的编程,前辈让我写一个包含数据库和前端的用户登录功能,通过看博客等我先是写了一个最基础的servlet+jsp,再到后来开始用maven进行编程,最终的完成版是一个 Spri ...

  3. Spring Boot 项目学习 (二) MySql + MyBatis 注解 + 分页控件 配置

    0 引言 本文主要在Spring Boot 基础项目的基础上,添加 Mysql .MyBatis(注解方式)与 分页控件 的配置,用于协助完成数据库操作. 1 创建数据表 这个过程就暂时省略了. 2 ...

  4. springBoot+mysql+mybatis demo [基本配置] [遇到的问题]

    springBoot+mysql+mybatis的基本配置: 多环境 application.properties spring.profiles.active=dev spring.applicat ...

  5. springboot学习笔记:8. springboot+druid+mysql+mybatis+通用mapper+pagehelper+mybatis-generator+freemarker+layui

    前言: 开发环境:IDEA+jdk1.8+windows10 目标:使用springboot整合druid数据源+mysql+mybatis+通用mapper插件+pagehelper插件+mybat ...

  6. springboot学习笔记:11.springboot+shiro+mysql+mybatis(通用mapper)+freemarker+ztree+layui实现通用的java后台管理系统(权限管理+用户管理+菜单管理)

    一.前言 经过前10篇文章,我们已经可以快速搭建一个springboot的web项目: 今天,我们在上一节基础上继续集成shiro框架,实现一个可以通用的后台管理系统:包括用户管理,角色管理,菜单管理 ...

  7. springboot学习笔记:10.springboot+atomikos+mysql+mybatis+druid+分布式事务

    前言 上一篇文章我们整合了springboot+druid+mybatis+mysql+多数据源: 本篇文章大家主要跟随你们涛兄在上一届基础上配置一下多数据源情况下的分布式事务: 首先,到底啥是分布式 ...

  8. mysql+mybatis 插入可递增字段库表操作

    mysql本身类型介绍: BIGINT 8 字节 (-9 233 372 036 854 775 808,9 223 372 036 854 775 807) (0,18 446 744 073 70 ...

  9. mysql,mybatis使用中遇到的类型转化的问题

    产生原因还没有明白,先记录一下. 使用DATEDIFF函数,计算两个日期的时间差.在mybatis中,resultType 是map.在代码中,根据map的key取值的时候. 在mysql 5.5.3 ...

  10. spring boot +mysql + mybatis + druid的整理(一)——单数据源

    一,使用spring boot脚手架搭建spring boot框架生成maven项目 如下图所示: 设置自定义的坐标,即左侧的Group和Artifact,右侧可以搜索添加一些依赖,搜索不到的可以在p ...

随机推荐

  1. PHP 程序员危机(转载)

    感谢有这样的机会,能和大家一起来聊聊开发者的那些事儿. 其实程序员危机是一个真实存在的问题.也有人说是互联网行业的下滑或者互联网行业已过了风口等等.我在这儿主要谈的是 PHP 程序员的危机,而这种危机 ...

  2. 常见mysql的慢查询优化方式

    一,第一步.开启mysql慢查询 方式一: 修改配置文件  在 my.ini 增加几行:  主要是慢查询的定义时间(超过2秒就是慢查询),以及慢查询log日志记录( slow_query_log) 方 ...

  3. Unity 让物体朝摄像机观察方向移动,已摇杆方向转向

    using System.Collections;using System.Collections.Generic;using UnityEngine; [RequireComponent(typeo ...

  4. 练手——用Python写的时间戳转换为北京时间的小工具

    #北京时间需加上8小时bj = 8*3600 def time_stamp(times):    #一天总秒数    nonDaySeconds = 24*3600    leapmonths = [ ...

  5. shell编辑器vi的常用命令

    一:翻页 ctrl+u向上翻半页 ctrl+f向上翻一页 ctrl+d 向下翻半页 ctrl+b 向下翻一页 二:移动光标指令 0: 光标移至当前行首 $: 光标移至当前行尾 三:常用插入.删除指令 ...

  6. iOS项目之iPhoneX遇到的坑

    问题一: 今天升级到Xcode 9.0,里面多了iPhone 8,iPhone 8P,iPhone X三款手机模拟器,而且发现最多可以同时运行五个模拟器.但随之而来的问题也出现了,就是 iPhone ...

  7. C语言实例:类型转换

    数组转换成16进制数: #include <stdio.h> #include <stdlib.h> typedef unsigned char UINT8; typedef ...

  8. Linux 主要目录速查表

    /:根目录,一般根目录下只存放目录,在 linux 下有且只有一个根目录,所有的东西都是从这里开始 当在终端里输入 /home,其实是在告诉电脑,先从 /(根目录)开始,再进入到 home 目录 /b ...

  9. windows版jmeter的body data如何用\n作为“换行”

    前段时间用jmeter进行某个web接口性能测试的时候遇到一个问题,body data中的换行的内容发送后,通过抓包发现总是发送"0D0A"即"\r\n"(wi ...

  10. ajax的三次封装简单概况

    原生ajax:                readyState         准备状态                status             页面状态               ...