SELECT tbl_user.`U_ID`,tbl_user.`U_USERNAME`,tbl_user.`U_TRUENAME`,tbl_user.`U_CREATETIME`,tbl_user.`U_STATE`,
GROUP_CONCAT(R_NAME SEPARATOR ',') as roles FROM tbl_role,tbl_user_role,tbl_user
WHERE tbl_user.`U_ID` = tbl_user_role.`UID` AND tbl_user_role.`RID` = tbl_role.`R_ID`
group by tbl_user.`U_ID`;
效果如下:
这条SQL 用到了 mysql的 group_concat 函数 使的角色由一列变为一行。
group by 按照用户id 分组,查找每个用户的所拥有的角色有哪些。
补充
<?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.imooc.auth.dao.UserMapper">
<!-- 利用 map 传递多个参数 -->
<select id="findUserAndRole" resultType="map" parameterType="map">
SELECT tbl_user.`U_ID`,tbl_user.`U_USERNAME`,tbl_user.`U_TRUENAME`,tbl_user.`U_CREATETIME`,tbl_user.`U_STATE`,
GROUP_CONCAT(R_NAME SEPARATOR ',') AS roles FROM tbl_user LEFT JOIN tbl_user_role ON tbl_user.`U_ID` = tbl_user_role.`UID`
LEFT JOIN tbl_role ON tbl_user_role.`RID` = tbl_role.`R_ID`
<where>
<if test="condition1 != null">
U_USERNAME like '%' #{condition1} '%'
</if>
<if test="condition1 != null">
OR U_TRUENAME like '%' #{condition1} '%'
</if>
</where>
GROUP BY tbl_user.`U_ID`
limit #{offset},#{rows};
</select>
</mapper>
- 左连接查询,即使用户没有角色,用户依然可以被查到。
- mybatis 的动态SQL,处理条件查询
- 注意 where 条件应该在 group by 的前面
- '%' 模糊查询 要加 ' ' 否则会报错
- 利用 map 传递多个参数,例如 分页的 offset(起始索引) ,rows(每页的大小) ,condition(查询条件)
- 起始索引 = (当前页号 - 1) * 每页大小,即 offset = (cuurentPage -1 ) * pageSize
(