1. 程式人生 > >Mysql專案相關sql大全_終身受用

Mysql專案相關sql大全_終身受用

1、Map型別的資料進行inset插入

有時候需要簡單地把一個Map中所有的key和value獲取出來,拼到sql語句中。MyBatis提供的一種方法是遍歷Map中的entrySet,然後把key扔進index裡面,value扔進item中。具體的一個使用的例子如下:

<insert id="operationName" parameterType="map">  
	    INSERT INTO table_name(hot_word, cnt)  
	    VALUES  
	    <foreach item="value" index="key" collection
="mapData.entrySet()" open="(" separator="),(" close=")">
#{key}, #{value} </foreach> ON DUPLICATE KEY UPDATE cnt=VALUES(cnt) </insert>

2、獲取資料結果為list<map<String,Object>>

1、mapper


public interface HealerJeanMapper {

     List<Map<String,
Object>
> sqlMap(); }

2、mapper.xml

<select id="sqlMap" resultType="java.util.HashMap">
  SELECT h.id as id ,h.subject as subject FROM  healerjean  h;
</select>

3、解釋:

1、返回型別必須是java.util.HashMap 2、map中的value 必須是Objecrt

4、controller測試


@RequestMapping("sqlMap")
@ResponseBody
public List<
Map<String,Object>> sqlMap(){ return healerJeanMapper.sqlMap(); }

3、mybatis 自定義引數、返回型別map

1、引數

<select id="getUserCount" parameterMap="getUserCountMap" statementType="CALLABLE"resultType="java.util.HashMap
>
        CALL ges_user_count(?,?)
 </select>     

<parameterMap type="java.util.Map" id="getUserCountMap">
   <parameter property="sexid" mode="IN" jdbcType="INTEGER"/>
   <parameter property="userCount" mode="OUT" jdbcType="INTEGER"/>
</parameterMap>

2、結果,返回欄位一一匹配,想想之前@Results和@Result


  <resultMap id="BaseResultMap" type="com.taotao.pojo.TbUser" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="phone" property="phone" jdbcType="VARCHAR" />
    <result column="email" property="email" jdbcType="VARCHAR" />
    <result column="created" property="created" jdbcType="TIMESTAMP" />
    <result column="updated" property="updated" jdbcType="TIMESTAMP" />
  </resultMap>


3、解釋 propertycolumn分別指定實體類屬性和資料表的列名。

4、If的使用

1、mapper介面

public interface CustomerMapper {

    List<Customer> findCustomerList( @Param("name") String name,
                                     @Param("status") Integer status,
                                     @Param("offset") Integer offset,
                                     @Param("limit") Integer limit);

}

2、mapper.xml sql’語句


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.duodian.admore.dao.mybatis.customer.CustomerMapper">

    <select id="findCustomerList" resultType="com.duodian.admore.entity.db.customer.Customer">
        SELECT t.* from crm_customer t
        WHERE t.isVisiblisVisiblee = 1
        <if test="name != null and name != ''">
            and t.name like CONCAT('%','${name}','%' )
        </if>
        <if test="status != null">
            and t.status = #{status}
        </if>
        order by t.id DESC
        limit #{offset}, #{limit}
    </select>

    <select id="countCustomerList" resultType="java.lang.Long">
        select count(*) from crm_customer t
        WHERE t.isVisible = 1
        <if test="name != null and name != ''">
            and t.name like CONCAT('%','${name}','%' )
        </if>
        <if test="status != null">
            and t.status = #{status}
        </if>
    </select>

</mapper>

5、where include的使用( 加入模糊查詢篩選條件)自帶去除第一個and

5.1、mapper


@Override
    public Page<SignetApplyRecord> findVerifySignetData(Long admId, Pageable pageable, SignetQuery query) {

        query.setStartDate(DateHelper.getDateFirstTime(query.getStartDate()));
        query.setEndDate(DateHelper.getDateLastTime(query.getEndDate()));
        query.setOffset(pageable.getOffset());
        query.setLimit(pageable.getPageSize());

              

        List<SignetApplyRecord> list = signetMapper.findVerifySignetList(query);
              

        Long count = signetMapper.countVerifySignet(query);

        return new PageImpl<>(list, pageable, count);
    }


5.2、xml

<select id="findVerifySignetList" resultType="com.duodian.admore.entity.db.signet.SignetApplyRecord">
    SELECT t.*,d.nickName userNickName,ifnull(e.realName,f.realName) userAuthName,b.name applyAdmName,ura.remittanceAccount
    FROM signet_apply_record t
    LEFT JOIN user d ON d.id = t.userId
    LEFT JOIN user_remittance_account ura ON ura.userId = t.userId
    <if test="currAdmId4Auth != null">
        LEFT JOIN sys_admin_user_customer h ON h.admId = #{currAdmId4Auth} AND h.userId = t.userId
        LEFT JOIN (SELECT wt.pid,count(*) cc FROM workflow_task_examine_details wte LEFT JOIN workflow_task wt ON wt.id = wte.taskId WHERE wt.taskType = 23 AND wte.admId = #{currAdmId4Auth} GROUP BY wt.pid) w ON w.pid = t.id
    </if>
    <where>
        <include refid="findVerifySignetWhere"></include>
    </where>
    order by t.id desc
    <if test="offset != null and limit != null">
        limit #{offset}, #{limit}
    </if>
</select>


<sql id="findVerifySignetWhere">
       <if test="taskTypeList != null and taskTypeList.size() > 0">
        and t.taskType IN
        <foreach collection="taskTypeList" index="index" item="at" open="(" separator="," close=")">
            #{at}
        </foreach>
    </if>
    <if test="signetType != null">
        and t.type = #{signetType}
    </if>
    <if test="status != null">
        and t.status = #{status}
    </if>
    <if test="currAdmId4Auth != null ">
        <![CDATA[ and (h.admId = #{currAdmId4Auth} OR w.cc > 0) ]]>
    </if>
</sql>

5.3、自帶去除第一個and


<select id="findUserAppsSpreadEffectList" resultType="com.duodian.admore.entity.db.apps.AppsSpreadEffectReport">
    SELECT t.*,b.trackName,b.smallIcon FROM apps_spread_effect_report t
    LEFT JOIN apps_user_app a ON a.trackId = t.trackId
    LEFT JOIN apps_app b ON b.trackId = t.trackId
    <where>
        <if test="userId != null">
            a.userId = #{userId}
        </if>
        <if test="startDate != null ">
            <![CDATA[ and t.spreadDate >=  #{startDate} ]]>
        </if>
        <if test="endDate != null ">
            <![CDATA[ and t.spreadDate <=  #{endDate} ]]>
        </if>
    </where>
    order by a.id desc
</select>



<!--自帶取去除第一個and-->
SELECT * FROM OD_LINK_TYPE
   <where>
       LINK_URI != BASE_TYPE_URI
       <if test="linkUri != null">
          AND LINK_URI LIKE '%${linkUri}%'
       </if>
       <if test="linkLabel != null">
           AND LINK_LABEL LIKE '%${linkLabel}%'
       </if>
       <if test="baseTypeUri != null">
           AND BASE_TYPE_URI=#{baseTypeUri}
       </if>
   </where>


6、、foreach list結合作為引數在mapper中的查詢(taskTypeList 為List)

 <if test="taskTypeList != null and taskTypeList.size() > 0"> and t.taskType IN
      <foreach collection="taskTypeList" index="index" item="at" open="(" separator="," close=")">
            #{at}
       </foreach>
</if>

<sql id="findVerifySignetWhere">
    <if test="startDate != null">
        <![CDATA[ and t.cdate >= #{startDate} ]]>
    </if>
    <if test="endDate != null">
        <![CDATA[ and t.cdate <= #{endDate} ]]>
    </if>
    <if test="userParam != null and userParam != '' and userParam!= 'undefined'">
        AND (t.userId = #{userParam} OR d.nickName LIKE CONCAT('%',#{userParam},'%' ) OR e.realName LIKE
        CONCAT('%',#{userParam},'%' ) OR f.realName LIKE CONCAT('%',#{userParam},'%' ) OR g.email LIKE
        CONCAT('%',#{userParam},'%' ))
    </if>
    <if test="taskType != null">
        and t.taskType = #{taskType}
    </if>
    <if test="taskTypeList != null and taskTypeList.size() > 0"> and t.taskType IN
      <foreach collection="taskTypeList" index="index" item="at" open="(" separator="," close=")">
            #{at}
       </foreach>
    </if>
    <if test="signetType != null">
        and t.type = #{signetType}
    </if>
    <if test="status != null">
        and t.status = #{status}
    </if>
    <if test="currAdmId4Auth != null ">
        <![CDATA[ and (h.admId = #{currAdmId4Auth} OR w.cc > 0) ]]>
    </if>
</sql>



7、choose when


<if test="flag != null">
    <choose>
        <when test="flag == 1">
            and t.status = 0
        </when>
        <when test="flag == 2">
            and t.status = 1
        </when>
        <when test="flag == 3">
            and t.expressStatus = 1
        </when>
        <when test="flag == 4">
            and t.status = -2
        </when>
    </choose>
</if>

8、ifnull (如果不是空返回第一個,否則返回第二個)

    ifnull(b.realName,c.realName) authName,


<select id="findRedStartSpread" parameterType="com.duodian.admore.dao.db.redstart.query.RedStartSpreadQuery" resultType="com.duodian.admore.dao.db.redstart.bean.RedStartHistoryBean">
    SELECT
    k.trackId,
    e.smallIcon,
    e.formattedPrice,
    e.price,
    e.fileSizeBytes,
    e.trackName,
    f.name admName,
    a.nickName userName,
    ifnull(b.realName,c.realName) authName,
    DATE_FORMAT(k.spreadDateStart, '%Y-%m-%d') AS ymd,
    k.userId
    FROM
    redstart_spread k


9。製作引數為map值進行傳入(opt專案SkinsController)

1、controller接收引數

@RequestMapping("data")
@ResponseBody
public ResponseBean data(String name,
					  Integer type,
					  Integer status,@RequestParam(value = "page",defaultValue = "0") Integer page){
  
        int pageSize = 15;
        Pageable pageable = new PageRequest(page,pageSize);
        Page<SkinAppInfoData> dataPage = skinsService.findSkinAppInfoList(pageable,"name",name,"type",type,"status",status);
        return ResponseBean.buildSuccess(dataPage);

}

2、service 製作map引數(下面的功能是模糊查詢?分頁)

1、service介面


public Page<SkinAppInfoData> findSkinAppInfoList(Pageable pageable, Object... param) throws AppException;

2、service開始實現 (pageable 主要是利用裡面的引數製作limit引數的)

@Override
public Page<SkinAppInfoData> findSkinAppInfoList(Pageable pageable, Object... param) throws AppException {
    Map data = MyBatisHelper.mergeParameterMap(pageable,param);

if(data.get("startDate") != null){
    Date startDate = (Date) data.get("startDate");
    data.put("startDate", com.duodian.admore.core.helper.DateHelper.getDateFirstTime(startDate));
}
if(data.get("endDate") != null){
    Date endDate = (Date) data.get("endDate");
    data.put("endDate", com.duodian.admore.core.helper.DateHelper.getDateLastTime(endDate));
}

    List<SkinAppInfoData> dataList = skinsMapper.findSkinList(data);

    for(SkinAppInfoData skinAppInfoData :dataList){
        List<ChannelJson> channelJsonList = new ArrayList<>();
        if(skinAppInfoData.getChannelJson()!=null&&!"".equals(skinAppInfoData.getChannelJson())) {
            JSONArray jsonArray = JSONArray.fromObject(skinAppInfoData.getChannelJson());
            for (int i = 0; i < jsonArray.size(); i++) {
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    ChannelJson channelJson = objectMapper.readValue(jsonArray.get(i).toString(), ChannelJson.class);
                    channelJsonList.add(channelJson);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        skinAppInfoData.setChannelJsonList(channelJsonList);

    }

    Long count = skinsMapper.countSkinList(data);
    return new PageImpl<SkinAppInfoData>(dataList,pageable,count);
}

3、MyBatisHelper工具欄


public class MyBatisHelper {
    public static final String PARAM_OFFSET = "offset";
    public static final String PARAM_LIMIT = "limit";

    public MyBatisHelper() {
    }

    public static Map<String, Object> mergeParameterMap(Object... parameter) {
        if (parameter.length % 2 != 0) {
            throw new IllegalArgumentException("parameter須為key-value對應引數");
        } else {
            Map<String, Object> map = new HashMap();

            for(int i = 0; i < parameter.length; i += 2) {
                map.put(parameter[i].toString(), parameter[i + 1]);
            }

            return map;
        }
    }

    public static Map<String, Object> mergeParameterMap(Pageable pageable, Object... parameter) {
        if (parameter.length % 2 != 0) {
            throw new 
            
           

相關推薦

Mysql專案相關sql大全_終身受用

1、Map型別的資料進行inset插入 有時候需要簡單地把一個Map中所有的key和value獲取出來,拼到sql語句中。MyBatis提供的一種方法是遍歷Map中的entrySet,然後把key扔進index裡面,value扔進item中。具體的一個使用的例子

MySQL語法大全_自己整理的學習筆記

用戶名 where ont mailto body 整理 若有 文本 密碼 select * from emp; #註釋 #---------------------------#----命令行連接MySql--------- #啟動mysql服務器net start

MySQL中關於SQL註入的相關需要的基礎知識

img 3.1 lock 默認 nts 3.4 不同 constrain 拼接 零、緒論:   文章部分整理來源於公司同事,特此鳴謝!!! 一、關於註入點在KEY上的註入: 我們來看一個查詢,你的第一個字段是過濾器(filter)第二個字段是查詢的關鍵字,例如查詢ip ==

Linux 中 shell jdk mysql ssh ntp yum相關配置..... 操作linux相關命令大全結構體系-思維導圖

以下是命令截圖:詳情連結連結:https://pan.baidu.com/s/1t1_6O_fOSi6atKWRvnE2vA  提取碼:px4y     該Linux結構知識體系——沒有crontab  cut  awk 等相關操作&nbs

mysql中查看錶結構相關sql

/**查看錶結構**/ desc yourtablename /**檢視建立表語句**/ show create table yourtablename /**檢視所有列的資訊**/ use informa

mysql在shell登入並執行相關sql

前言 場景:通過指令碼執行建立資料庫,建立表等相關的語句,這時候就得不登入mysql就能直接執行相關的語句。mysql也提供了一系列的命令和引數。 https://dev.mysql.com/doc/ 應用例子 列出所有的資料庫 [[email protected] opt]# my

Linux 首先基本包安裝(vim啊什麼的),源,源優化,專案架構介紹, (LNMuWsgi)Django專案相關軟體mysql,redies,python(相關模組)安裝配置測試

內容 補充: 檢視已啟動服務的埠 netstat -tulnp |grep 80(方式1) ss -tulnp|grep 80(方式2) 前期鋪墊: 1. Linux要能上網 2. 掌握Linux軟體包安裝方法 2.1 rpm包管理 軟體包格式:名字-版本-平臺-rpm 建議

MySQL 抓取SQL慢查詢語句

mysql 索引 數據表 sql慢查詢 逗哥自動化 當MySQL服務器出現異常(慢),首先要考慮是否因,SQL語句引起數據庫慢,如果情況比較緊急,我們就要立刻 SHOW FULL PROCESSLIST; 去查看,但我建議大家使用-e參數,采用非交互的方式,因為這樣可以使用grep

虛擬機相關問題大全

內存 相關 ask font class cpu 核心數 增加 重置 Q1.客戶機操作系統已禁用 cpu 請關閉或重置虛擬機,如何解決? Answer1:內存分配不足;重新分配:點擊“虛擬機設置”--》“此虛擬機的內存+”---》“處理器數量+ /每個處理器的核心數

MySQL專題3 SQL 優化

prim ofa 建立 運行 關註 intersect order by 獲得 專題 這兩天去京東面試,面試官問了我一個問題,如何優化SQL 我上網查了一下資料,找到了不少方法,做一下記錄 (一)、 首先使用慢查詢分析 通過Mysql 的Slow Query log

基於mysql的一些sql語法

文本搜索 print use 客戶 .com fault lac images 磁盤 p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 } p.p2 {

mysql如何配置sql記錄

lean edit target 似的 51cto put cto www 不同 原文鏈接:http://www.qqdeveloper.com/detail/11/1.html 為什麽要記錄sql記錄 主要目的是為了檢測我們的網站安全問題,有效的避免一些sql註入或者是x

【薦讀】《我的前半生》:無論哪個階層,這8條職場潛規則都終身受用

態度 mil 排列組合 進階 金錢 -c 收入 我不 inline 【薦讀】《我的前半生》:無論哪個階層,這8條職場潛規則都終身受用 2017-07-19人民日報1職場沒有捷徑好走的路都不是坦途劇:做全職太太10年養尊處優的羅子君,早就和職場脫節,但為了與前夫爭奪兒子的

[flask實踐] 解決qq郵箱/mysql相關配置問題

信息 fig config connect 我們 web服務 哪些 流程 點擊 筆者經過flask web(Miguel著,封面是一條狗)一書的學習,打算實現一個旅遊類網站,在此過程中發現,相對於書中的flasky博客程序,需要作出一些改變: 1. 註冊郵箱:國內要使用12

MySQL查看SQL語句執行效率

博客 union pan art 顯示 uniq left join 匹配 article Explain命令在解決數據庫性能上是第一推薦使用命令,大部分的性能問題可以通過此命令來簡單的解決,Explain可以用來查看 SQL 語句的執行效 果,可以幫助選擇更好的索引和優化

有關apache+php+mysql相關下載及配置

load nbsp image pac 點擊 mysql windows 相關 php 01. Apache的下載及配置   apache的下載地址:http://httpd.apache.org 點擊:download下載 之後跳轉 點擊:Files

MySQL階段二——sql語句基礎(2)

mysql數據查詢操作 01.創建數據表 (02-05練習) (連接查詢練習使用) 02.單表查詢 03.分組統計 04.嵌套查詢 05.集合查詢 06.連接查詢 07.連接查詢與集合查詢的不同 數據查詢操作01.創建數據表 1)創建Student表 (2)創建Course表

MySQL階段二——sql語句基礎(3)

mysqlOutfile 註意: Insert詳解 delete和update相關 視圖 01.視圖創建 02.視圖相關定義 03.視圖創建詳解 04.刪除視圖 05.視圖查詢 06.更新視圖 07.視圖的執行過程 觸發器 01.定義觸發器 02.操作觸發器 03.註意 Outfile將

MySQL運維命令大全

mysql命令大全 mysql運維 關系型數據庫DML: Data Manapulate Lanauage 數據操作語言 INSERT, REPALCE, UPDATE, DELETEDDL: Data Definition Lanauage 數據定義語言 CREATE, ALT

mysql 日誌文件mysql-bin文件清除方法,和mysql-bin相關文件的配置

設置 row exp ted 基本 安全 ret 保留 span 默認情況下mysql會一直保留mysql-bin文件,這樣到一定時候,磁盤可能會被撐滿,這時候是否可以刪除這些文件呢,是否可以安全刪除,是個問題。 首先要說明一下,這些文件都是mysql的日誌文件,如果不做主