复杂SQL语句的书写(mybatis中XML文件的核心)

select
		sd.name as dptName,
		pro.`name` as provinceName,
    	c.`name` as cityName,
		a.`name` as areaName,
		info.id,
		dpt.*,
		info.*,
		gd.*
    	from info_sys as info
    	left join depart as dpt on dpt.dept_namee = info.dept_namee
		left join grade as gd on gd.info_sys_id = info.id
		left join sys_dept as sd  on dpt.dept_namee = sd.dept_id
		left join province pro on dpt.province = pro.code_p
    	left join city c on dpt.city = c.code_c
		left join area a on dpt.area = a.code_a
		where info.id = #{id}

以上是李大哥写的

以下是我写的

select
		info.`id`,
		info.`dept_namee`,
		dpt.`principal_name`,
		dpt.`unit_type`,
		info.`sys_name`,
		info.`dept_name`,
		info.`begin_use_time`,
		gd.`pro_grade`,
		gd.`pro_time`,
		gd.`jug_res`,
		gd.`gov_res`
		from depart as dpt
		left join info_sys as info on dpt.dept_namee = info.dept_namee
		left join grade as gd on gd.info_sys_id = info.id

在写多表联合sql语句的时候:

1、如果是要拼接where条件语句,那么where语句中的内容用#{id}

实例:

where info.id = #{id}

如果where语句中的条件语句写在里边的话,那么就要拼接。

还需要做if条件判断。

<where>

    <if test = "id != null and id != ' '"> id = #{value}</if>

   </where>

2、后边还可以加排序:

<choose>

<when  test = " sort != null and sort.trim() != ' '">

order by ${sort} ${order}

</when>

<otherwise>

order by id desc

</choose>

3、分页

<if>

limit  ${offset} ${limit} 

</if>

以上是要写在select框中的。

4、在写多表联合查询语句的时候,不是下一个表的外键和上一个表的主键相等这么对应的,而是:

两张表中的相对应的字段相等,这么对应的。

5、还可以使用as将查询到的语句字段,后边加上别名。

在查询语句中:result type的类型

①当使用select进行查询的时候,返回的result type的类型必须是实体类的字段的类型。查询语句后边常常要加上很多的条件。

②当使用update更新的时候,paremet type的类型必须是实体类中的类型。update更新的时候,后边只需要加上ID一个条件就成

③当使用insert插入的时候,result type的类型必须是实体类的类型。insert后边不需要加条件。

useGeneratedKeys="true" keyProperty="id" 是什么意思呢?

④当使用delete的时候,直接删除就可以。delete * from table where id = #{id}到底是#{id} 还是#{value},这两个写法里边是什么区别?

⑤当使用batch remove的时候,批量删除。里边需要使用循环。

<delete id = "batchRemove">

delete table from table where id in

<foreach item = "id" collection = "array" open = "(" seperator = "," close = ")">

 #{id}

</foreach>

</delete>

⑥使用distinct 查询

<select id="listType" resultType="com.bootdo.common.domain.DictDO">
   select distinct `type` , description from sys_dict
</select>

猜你喜欢

转载自blog.csdn.net/wyqwilliam/article/details/83588902
今日推荐