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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM