MYSQL mybatis

 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

原文地址:https://www.cnblogs.com/Gift/p/10429591.html