关于sql的一些学习
关于trim标签的使用
| 属性 | 描述 |
|---|---|
| prefix | 给sql语句拼接的前缀 |
| suffix | 给sql语句拼接的后缀 |
| prefixOverrides | 去除sal语句前面的关键字或者字符,该关键字或者字符由prefxOverrides属性指定,假设该属性指定为”AND”,当sql语句的开头为”AND”,trim标签将会去除该”AND” |
| suffixOverrides | 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定 |
例如下面的sql语段1
2
3
4<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="name != null">name,</if>
</trim>
就是在sql中将前缀拼接为”(“,后缀拼接为”)”,并且去除后缀的”,”。
关于sql语句的解耦
在sql编写中,我们可以将多次出现的sql语句进行抽离并调用,这样大大降低了sql的耦合度
例如1
2select id, name, parent_id from test where id = #{id}
select id, name, parent_id from test where name = #{name}
以上的sql可以抽离为1
2
3
4
5
6
7
8
9
10
11
12
13<sql id="selectTest">
select id, name, parent_id from test
</sql>
<select id="selectById">
<include refid="selectTest"/>
where id = #{id}
</select>
<select id="selectByName">
<include refid="selectTest"/>
where name = #{name}
</select>
关于distinct关键字
在sql语句中,我们可以使用distinct关键字来去除重复的记录
例如有下表
当我们使用distinct查询表时,返回的表数据会自动去重1
select distinct name, age from test

其中重复的Alice记录就只能显示一个了
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 精神内猫!



