mysql組織機構樹迭代查詢
組織機構表結構
建表語句
drop table if exists Organize;
/*==============================================================*/
/* Table: Organize */
/*==============================================================*/
create table Organize
(
ID smallint not null auto_increment,
ORG_NAME int,
UP_ID int,
ORG_CODE char(4),
primary key (ID)
);
初始化資料
迭代查詢組織結構
oracle裡面有迭代函式可用,
select XXX from table
start with XXX
connect by prior XXX
mysql沒有類似的迭代函式,需要自己寫
建立函式語句
CREATE FUNCTION `getChildLst`(rootId INT)
RETURNS varchar(1000)
BEGIN
DECLARE sTemp VARCHAR(1000);
DECLARE sTempChd VARCHAR(1000);
SET sTemp = ‘$’;
SET sTempChd =cast(rootId as CHAR);
WHILE sTempChd is not null DO
SET sTemp = concat(sTemp,’,’,sTempChd);
SELECT group_concat(id) INTO sTempChd FROM organize where FIND_IN_SET(up_id,sTempChd)>0;
END WHILE;
RETURN sTemp;
END
查詢語句如下(增加模糊條件可以對迭代查詢後的資料進行篩選)
select o.ID orgId,o.ORG_CODE orgCode,o.ORG_NAME orgName from organize o
where FIND_IN_SET(id, getChildLst(45)) and o.ORG_NAME like ‘%%’;
關鍵是mybatis如何實現動態sql
mybatis對映檔案配置如下:
<resultMap id=”OrgInfoListPageMap” type=”com.znyq.wfCloud.service.pageModel.OrgInfolistPage” >
<result column=”orgId” property=”orgId” jdbcType=”SMALLINT” />
<result column=”orgName” property=”orgName” jdbcType=”VARCHAR” />
<result column=”orgCode” property=”orgCode” jdbcType=”CHAR” />
</resultMap>
<select id=”findOrgInfListPage” resultMap=”OrgInfoListPageMap” parameterType=”java.lang.String”>
select o.ID orgId,o.ORG_CODE orgCode,o.ORG_NAME orgName from organize o
<where>
<if test=”orgId != null and ” != orgId” >
FIND_IN_SET(id, getChildLst(#{orgId}))
</if>
<if test=”orgName != null and ” != orgName” >
and o.ORG_NAME like CONCAT(CONCAT(‘%’, #{orgName}), ‘%’)
</if>
</where>
</select>
對映的物件
public class OrgInfolistPage {
private String orgId;
private String orgCode;
private String orgName;
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
}
OrganizeMapper:
List<OrgInfolistPage> findOrgInfListPage(@Param(value=”orgId”)String orgId,@Param(value=”orgName”)String orgName);