sql 与 xml中的sql

Posted 三王的笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 与 xml中的sql相关的知识,希望对你有一定的参考价值。

1. 数据库时间格式批量修改

利用DATE_FORMAT函数批量修改时间格式

UPDATE `T_REQUIRE` SET START_DT = DATE_FORMAT(START_DT,'%Y-%m-%d %H:%i:%S');

UPDATE `T_REQUIRE` SET FINISHED_DT = DATE_FORMAT(FINISHED_DT,'%Y-%m-%d %H:%i:%S');


利用DATE_ADD()DATE_SUB()函数为数据库中的某一时间列增减时间段

语法 DATE_ADD(date,INTERVAL expr type) DATE_SUB(date,INTERVAL expr type)

date 参数是合法的日期表达式。

expr参数是您希望添加的时间间隔。

type 参数可以是下列值:

More ActionsType 值:

MICROSECOND ,SECOND,MINUTE,HOUR,DAY, WEEK, MONTH,QUARTER ,YEAR, SECOND_MICROSECOND ,MINUTE_MICROSECOND,MINUTE_SECOND,HOUR_MICROSECOND,HOUR_SECOND,HOUR_MINUTE,DAY_MICROSECOND,DAY_SECOND,DAY_MINUTE ,DAY_HOUR,YEAR_MONTH


UPDATE `T_REQUIRE` SET START_DT = DATE_SUB(START_DT, INTERVAL 8 HOUR) ;-- 减去8小时
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 8 HOUR) ;-- 加上8小时
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 1 DAY) ;-- 加1天
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 1 minute) ;-- 加1分钟
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 1 second) ;-- 加1秒
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 1 microsecond) ;-- 加1毫秒
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 1 week) ;-- 加1周
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 1 month) ;-- 加1月
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 1 quarter) ;-- 加1季
UPDATE `T_REQUIRE` SET START_DT = DATE_ADD(START_DT, INTERVAL 1 year) ;-- 加1年


Type 值:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH


2. 根据字段的不同值执行不同的方法

status不等于6的数据计算T_TASK_SCHEDULE表的SCHEDULE_SCORE的和作为score,status等于6的记录存储T_USER_SCORE_EVENT表中对应的score值

关键语法CASE WHEN  条件  THEN 执行语句1 ELSE 执行语句2 END

SELECT a.id AS id,
a.TASK_TITLE AS taskTitle,
e.PROJECT_NAME AS projectName,
a.PRIORITY AS priority,
a.`STATUS` AS STATUS,
a.PARENT_ID AS parentId,
      c.REAL_NAME AS executorName,
      SUM(f.CONSUME_TIME) AS totalTime,
      a.START_DT AS startDt,
      a.FINISHED_DT AS finishedDt,
      a.EXPECTED_TIME AS expectedTime,
      a.DIFF_RATIO AS diffRatio,
      b.`COMMENT` AS reviewComment,
      CASE WHEN a.`STATUS` !='6' THEN SUM(f.SCHEDULE_SCORE)
  ELSE b.SCORE END AS score
       FROM T_TASK AS a
      LEFT JOIN T_TASK_EXECUTOR AS g ON a.ID = g.TASK_ID
      LEFT JOIN T_USER_SCORE_EVENT AS b ON b.TASK_ID = a.ID
      LEFT JOIN T_USER AS c ON c.ID = g.TASK_EXE_USER_ID
      LEFT JOIN T_PROJECT_TASK_REL AS d ON d.TASK_ID = a.ID
      LEFT JOIN T_PROJECT AS e ON e.ID = d.PROJECT_ID
      LEFT JOIN T_TASK_SCHEDULE AS f ON f.TASK_ID = a.ID
       WHERE
      a.`STATUS` !='1' AND a.VALIDATE = '1' AND a.PARENT_ID !='0'
               GROUP BY a.ID
       HAVING totalTime > 0;



3. 自定义实现mybatisPlus中的updateById方法

表结构

CREATE TABLE `dict_val` (
`val_id` bigint(16) NOT NULL AUTO_INCREMENT COMMENT '主键',
`p_val_id` bigint(16) NOT NULL DEFAULT '-1' COMMENT '父字典',
`key_id` bigint(16) NOT NULL COMMENT 'dict_key表主键',
`code` varchar(64) DEFAULT NULL COMMENT '编码',
`val` varchar(64) DEFAULT NULL COMMENT '内容',
`nation_code` varchar(64) DEFAULT NULL COMMENT '国标编码',
`nation_val` varchar(64) DEFAULT NULL COMMENT '国标内容',
`input_code` varchar(32) DEFAULT NULL COMMENT '拼音码',
`input_code_wb` varchar(32) DEFAULT NULL COMMENT '五笔码',
`input_code_zjm` varchar(32) DEFAULT NULL COMMENT '助记码',
`input_code_bym` varchar(32) DEFAULT NULL COMMENT '备用码',
`enable` varchar(2) DEFAULT NULL COMMENT '有效标志位',
`order` int(16) DEFAULT NULL COMMENT '排序',
`memo` varchar(128) DEFAULT NULL COMMENT '备注',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`create_id` bigint(16) DEFAULT NULL COMMENT '创建人',
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',
`update_id` bigint(16) DEFAULT NULL COMMENT '最后更新人',
PRIMARY KEY (`val_id`),
KEY `idx_dict_val_01` (`key_id`),
KEY `idx_dict_val_02` (`code`),
KEY `idx_dict_val_03` (`input_code`),
KEY `idx_dict_val_04` (`input_code_wb`),
KEY `idx_dict_val_05` (`input_code_zjm`),
KEY `idx_dict_val_06` (`input_code_bym`),
KEY `idx_dict_val_07` (`nation_code`),
KEY `idx_dict_val_08` (`nation_val`),
KEY `idx_dict_val_09` (`p_val_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6689805943284170754 DEFAULT CHARSET=utf8mb4 COMMENT='字典数据表'

DictVal实体类

@Data
@TableName("dict_val")
public class DictVal extends Model<DictVal> {
   private static final long serialVersionUID = 1L;

   /**
    * 主键
    */
   @TableId(value = "val_id", type = IdType.AUTO)
   private Long valId;
   /**
    * 父字典
    */
   @TableField("p_val_id")
   private Long pValId;
   /**
    * dict_key表主键
    */
   @TableField("key_id")
   private Long keyId;
   /**
    * 编码
    */
   private String code;
   /**
    * 内容
    */
   private String val;
   /**
    * 国标编码
    */
   @TableField("nation_code")
   private String nationCode;
   /**
    * 国标内容
    */
   @TableField("nation_val")
   private String nationVal;
   /**
    * 拼音码
    */
   @TableField("input_code")
   private String inputCode;
   /**
    * 五笔码
    */
   @TableField("input_code_wb")
   private String inputCodeWb;
   /**
    * 助记码
    */
   @TableField("input_code_zjm")
   private String inputCodeZjm;
   /**
    * 备用码
    */
   @TableField("input_code_bym")
   private String inputCodeBym;

   /**
    * 有效标志位
    */
   private String enable;
   /**
    * 排序
    */
   private Integer order;
   /**
    * 备注
    */
   private String memo;
   /**
    * 创建时间
    */
   @TableField("create_time")
   private Date createTime;
   /**
    * 创建人
    */
   @TableField("create_id")
   private Long createId;
   /**
    * 最后更新时间
    */
   @TableField("update_time")
   private Date updateTime;
   /**
    * 最后更新人
    */
   @TableField("update_id")
   private Long updateId;

}

mapper文件

注意,此mapper方法不能使用@Param注解,使用后if中的test内判断条件不生效!

int updateByValId(DictVal dictVal);

xml文件

<trim>标签标识修剪

prefix:前缀O

prefixOverrides:去掉第一个所写的内容

suffix:后缀

suffixOverride:去掉最后一个所写的内容(此处为逗号)

<update id="updateByValId">
  UPDATE `dict_val`
   <trim prefix="SET" suffixOverrides=",">
<if test="pValId != null and pValId != ''">
`p_val_id` = #{pValId},
</if>
<if test="keyId != null and keyId != ''">
`key_id` = #{keyId},
</if>
<if test="code != null and code != ''">
`code` = #{code},
</if>
<if test="val != null and val != ''">
`val` = #{val},
</if>
<if test="nationCode != null and nationCode != ''">
`nation_code` = #{nationCode},
</if>
<if test="nationVal != null and nationVal != ''">
`nation_val` = #{nationVal},
</if>
<if test="inputCode != null and inputCode != ''">
`input_code` = #{inputCode},
</if>
<if test="inputCodeWb != null and inputCodeWb != ''">
`input_code_wb` = #{inputCodeWb},
</if>
<if test="inputCodeZjm != null and inputCodeZjm != ''">
`input_code_zjm` = #{inputCodeZjm},
</if>
<if test="inputCodeBym != null and inputCodeBym != ''">
`input_code_bym` = #{inputCodeBym},
</if>
<if test="enable != null and enable != ''">
`enable` = #{enable},
</if>
<if test="order != null and order != ''">
`order` = #{order},
</if>
<if test="memo != null and memo != ''">
`memo` = #{memo},
</if>
<if test="createId != null and createId != ''">
`create_id` = #{createId},
</if>
<if test="updateId != null and updateId != ''">
`update_id` = #{updateId},
</if>
   </trim>
  WHERE `val_id`=#{valId}
</update>


4. 自定义实现mybatisPlus中的insert方法

实体类和数据库模型参考第16条

mapper文件

int create(@Param("dictVal") DictVal dictVal);

xml文件

<sql id="base_post_colume">
  `p_val_id`,
  `key_id`,
  `code`,
  `val`,
  `nation_code`,
  `nation_val`,
  `input_code`,
  `input_code_wb`,
  `input_code_zjm`,
  `input_code_bym`,
  `enable`,
  `order`,
  `memo`,
  `create_id`,
  `update_id`
</sql>
<sql id="base_post_val">
  #{dictVal.pValId},
  #{dictVal.keyId},
  #{dictVal.code},
  #{dictVal.val},
  #{dictVal.nationCode},
  #{dictVal.nationVal},
  #{dictVal.inputCode},
  #{dictVal.inputCodeWb},
  #{dictVal.inputCodeZjm},
  #{dictVal.inputCodeBym},
  #{dictVal.enable},
  #{dictVal.order},
  #{dictVal.memo},
  #{dictVal.createId},
  #{dictVal.updateId}
</sql>

<insert id="create">
  INSERT into `dict_val` (<include refid="base_post_colume"/>)
  VALUES (<include refid="base_post_val"/>)
</insert>


5. 自定义新增修改

    int testupdateproject(Project project);//实现若有值则修改,无值不变

   int testinsert(@Param("project") Project project);


<update id="testupdateproject" parameterType="com.cnsesan.shennong.kanban.entity.Project">
      UPDATE T_PROJECT
       <trim prefix="SET" suffixOverrides=",">
       <if test="projectName != null and projectName != ''">
          PROJECT_NAME = #{projectName},
       </if>
       <if test="projectDesc != null and projectDesc != ''">
          PROJECT_DESC = #{projectDesc},
       </if>
       <if test="expectedDay != null and expectedDay != ''">
          EXPECTED_DAY = #{expectedDay},
       </if>
       <if test="projectType != null and projectType != ''">
          PROJECT_TYPE = #{projectType},
       </if>
       </trim>
      WHERE ID = #{id}
   </update>

   <insert id="testinsert">
      INSERT into T_PROJECT (ID,PROJECT_NAME,PROJECT_DESC,START_DT,FINISHED_DT,PROJECT_TYPE,EXPECTED_DAY,VALIDATE,CREATED_BY,CREATED_TIME,UPDATED_BY,UPDATED_TIME,PARENT_ID)
      VALUES (#{project.id},#{project.projectName},#{project.projectDesc},#{project.startDt},#{project.finishedDt},#{project.projectType},
      #{project.expectedDay},#{project.validate},#{project.createdBy},#{project.createdTime},#{project.updatedBy},#{project.updatedTime},
      #{project.parentId})
   </insert>


6. 批量修改

mybatis

 int updateBatchs(@Param("list") List<PhyExamInfoItemRes> list);
<update id="updateBatchs" parameterType="java.util.List">
update `phy_exam_info_item_res`
<trim prefix="set" suffixOverrides=",">
<trim prefix="`info_item_id` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.infoItemId !=null and item.infoItemId != ''">
when #{item.resId} then #{item.infoItemId}
</if>
</foreach>
</trim>
<trim prefix="`hos_id` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.hosId !=null and item.hosId != ''">
when #{item.resId} then #{item.hosId}
</if>
</foreach>
</trim>
<trim prefix="`item_name` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.itemName !=null and item.itemName != ''">
when #{item.resId} then #{item.itemName}
</if>
</foreach>
</trim>
<trim prefix="`result` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.result !=null and item.result != ''">
when #{item.resId} then #{item.result}
</if>
</foreach>
</trim>
<trim prefix="`units` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.units !=null and item.units != ''">
when #{item.resId} then #{item.units}
</if>
</foreach>
</trim>
<trim prefix="`mark` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.mark !=null and item.mark != ''">
when #{item.resId} then #{item.mark}
</if>
</foreach>
</trim>
<trim prefix="`exam_sub_class` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.examSubClass !=null and item.examSubClass != ''">
when #{item.resId} then #{item.examSubClass}
</if>
</foreach>
</trim>
<trim prefix="`result_status_code` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.resultStatusCode !=null and item.resultStatusCode != ''">
when #{item.resId} then #{item.resultStatusCode}
</if>
</foreach>
</trim>
<trim prefix="`result_status_name` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.resultStatusName !=null and item.resultStatusName != ''">
when #{item.resId} then #{item.resultStatusName}
</if>
</foreach>
</trim>
<trim prefix="`show_type` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.showType !=null and item.showType != ''">
when #{item.resId} then #{item.showType}
</if>
</foreach>
</trim>
<trim prefix="`exe_time` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.exeTime !=null and item.exeTime != ''">
when #{item.resId} then #{item.exeTime}
</if>
</foreach>
</trim>
<trim prefix="`conclusion` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.conclusion !=null and item.conclusion != ''">
when #{item.resId} then #{item.conclusion}
</if>
</foreach>
</trim>
<trim prefix="`update_id` = case `res_id`" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.updateId !=null and item.updateId != ''">
when #{item.resId} then #{item.updateId}
</if>
</foreach>
</trim>
</trim>
where `res_id` in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.resId}
</foreach>
</update>


7. 批量新增

mapper

int insertBatchs(@Param("list") List<PhyExamInfoItemRes> list);
<insert id="insertBatchs" parameterType="java.util.List">
insert into `phy_exam_info_item_res`
(`info_item_id`,`hos_id`, `bill_order`,
`print_order`, `item_code`,`item_name`, `result`, `units`,
`instrument_id`,`result_date`,`print_info`, `mark`, `report_id` ,
`report_name`, `exam_sub_class`,`description`, `impression`, `recommendation`,
`result_status_code`,`result_status_name`,`exam_pdf_path` , `exam_report_url`,
`show_type`, `exe_time`,`conclusion`,`enable`, `create_id`,`update_id`) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.infoItemId,jdbcType=BIGINT},#{item.hosId,jdbcType=BIGINT},#{item.billOrder,jdbcType=VARCHAR},
#{item.printOrder,jdbcType=VARCHAR},#{item.itemCode,jdbcType=VARCHAR},#{item.itemName,jdbcType=VARCHAR},
#{item.result,jdbcType=VARCHAR},#{item.units,jdbcType=VARCHAR},
#{item.instrumentId,jdbcType=VARCHAR},#{item.resultDate,jdbcType=VARCHAR},#{item.printInfo,jdbcType=VARCHAR},
#{item.mark,jdbcType=VARCHAR},#{item.reportId,jdbcType=VARCHAR},
#{item.reportName,jdbcType=VARCHAR},#{item.examSubClass,jdbcType=VARCHAR},#{item.description,jdbcType=VARCHAR},
#{item.impression,jdbcType=VARCHAR},#{item.recommendation,jdbcType=VARCHAR},
#{item.resultStatusCode,jdbcType=VARCHAR},#{item.resultStatusName,jdbcType=VARCHAR},
#{item.examPdfPath,jdbcType=VARCHAR},#{item.examReportUrl,jdbcType=VARCHAR},
#{item.showType,jdbcType=VARCHAR},#{item.exeTime,jdbcType=DATE},
#{item.conclusion,jdbcType=VARCHAR},'1',
#{item.createId,jdbcType=BIGINT},#{item.updateId,jdbcType=BIGINT})
</foreach>
</insert>


8. mysql字符串拼接

  1、CONCAT函数

语法格式:CONCAT(char c1, char c2, ..., char cn) ,其中char代表字符串,定长与不定长均可以

  1.1)连接两个字符串

  1.2)连接多个字符串

sql 与 xml中的sql

  2、"+"操作符

  2.1)连接两个字符串

sql 与 xml中的sql

  2.2)连接多个字符串

sql 与 xml中的sql

  3、假如其中一个字段为NULL,则用结果用空格代替NULL。

sql 与 xml中的sql


9. xml文件中处理大于小于号

  1. 用转义字符处理

    SELECT * FROM test WHERE 1 = 1 AND start_date  html_entity" data-content="<" class="mq-2313"><= CURRENT_DATE AND end_date >= CURRENT_DATEsql 与 xml中的sql

  2. <![CDATA[ ]]>符号进行说明

<![CDATA[ when min(starttime)<='12:00' and max(endtime)<='12:00' ]]>


10. sql的in的局限和优化

sql 与 xml中的sql

in 的最大查询量为1000;超过1000,sql 就会报错。

解决方法1:缺点是sql中不能含有sum等计算

11. mybatis框架xml文件中jdbcType相关

sql中的jdbcType值必须大写

<insert id="insertBatchs" parameterType="java.util.List">
insert into `phy_exam_info_item_res`
(`info_item_id`,`hos_id`, `bill_order`,
`print_order`, `item_code`,`item_name`, `result`, `units`,
`instrument_id`,`result_date`,`print_info`, `mark`, `report_id` ,
`report_name`, `exam_sub_class`,`description`,`impression`,`recommendation`,
`result_status_code`,`result_status_name`,`exam_pdf_path`,`exam_report_url`,
`show_type`, `exe_time`,`enable`, `create_id`,`update_id`) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.infoItemId,jdbcType=BIGINT},#{item.hosId,jdbcType=BIGINT},
          #{item.billOrder,jdbcType=VARCHAR},
#{item.printOrder,jdbcType=VARCHAR},#{item.itemCode,jdbcType=VARCHAR},
          #{item.itemName,jdbcType=VARCHAR},
#{item.result,jdbcType=VARCHAR},#{item.units,jdbcType=VARCHAR},
#{item.instrumentId,jdbcType=VARCHAR},
          #{item.resultDate,jdbcType=VARCHAR},#{item.printInfo,jdbcType=VARCHAR},
#{item.mark,jdbcType=VARCHAR},#{item.reportId,jdbcType=VARCHAR},
#{item.reportName,jdbcType=VARCHAR},
          #{item.examSubClass,jdbcType=VARCHAR},
          #{item.description,jdbcType=VARCHAR},
#{item.impression,jdbcType=VARCHAR},
          #{item.recommendation,jdbcType=VARCHAR},
#{item.resultStatusCode,jdbcType=VARCHAR},
          #{item.resultStatusName,jdbcType=VARCHAR},
#{item.examPdfPath,jdbcType=VARCHAR},
          #{item.examReportUrl,jdbcType=VARCHAR},
#{item.showType,jdbcType=VARCHAR},#{item.exeTime,jdbcType=DATE},'1',
#{item.createId,jdbcType=BIGINT},#{item.updateId,jdbcType=BIGINT})
</foreach>
</insert>

12. sql若字段为空修改,否则不修改

UPDATE phy_exam_info SET last_print_date = CURRENT_TIMESTAMP,
pri_print_date = (CASE WHEN pri_print_date IS NULL THEN CURRENT_TIMESTAMP ELSE pri_print_date END )
WHERE pe_id IN (6724850696132231169,6724851301449990145);


13. 查询字段相同的sql

SELECT TASK_ID,COUNT(*) AS COUNT FROM T_USER_SCORE_EVENT GROUP BY TASK_ID HAVING COUNT>1;






以上是关于sql 与 xml中的sql的主要内容,如果未能解决你的问题,请参考以下文章

使用实体框架迁移时 SQL Server 连接抛出异常 - 添加代码片段

MyBatis之Mapper XML 文件详解-sql和入参

sql sql里面的代码片段

sql 与 xml中的sql

mybatis-基于xml的多表查询

如何将 sql 中的两个 xml 与出现的节点进行比较?