簡介
在orm框架中,比如hibernate和mybatis都可以設(shè)置關(guān)聯(lián)對(duì)象,比如user對(duì)象關(guān)聯(lián)dept
假如查詢出n個(gè)user,那么需要做n次查詢dept,查詢user是一次select,查詢user關(guān)聯(lián)的
dept,是n次,所以是n+1問題,其實(shí)叫1+n更為合理一些。
mybatis配置
UserMapper.xml
resultMap id="BaseResultMap" type="testmaven.entity.User">
id column="id" jdbcType="INTEGER" property="id" />
result column="name" jdbcType="VARCHAR" property="name" />
result column="age" jdbcType="INTEGER" property="age" />
result column="dept_id" jdbcType="INTEGER" property="deptId" />
association property="dept" column="dept_id" fetchType="eager" select="testmaven.mapper.DeptMapper.selectByPrimaryKey" >/association>
/resultMap>
數(shù)據(jù)表如下:
department表
|id|name|
user表
|id|name|department_id|
需求是得到以下結(jié)構(gòu)的數(shù)據(jù):
[
{ "id":1, "name":"test", "department_id":1, "department":{ "id":1, "name":"測試部門"
}
}
]
方法一:循環(huán)查詢
查詢用戶列表
循環(huán)用戶列表查詢對(duì)應(yīng)的部門信息
$users = $db->query('SELECT * FROM `user`');foreach($users as $user) {
$users['department'] = $db->query('SELECT * FROM `department` WHERE `id` = '.$user['department_id']);
}
該方法查詢次數(shù)為:1+N(1次查詢列表,N次查詢部門),性能最低,不可取。
方法二:連表
通過連表查詢用戶和部門數(shù)據(jù)
處理返回?cái)?shù)據(jù)
$users = $db->query('SELECT * FROM `user` INNER JOIN `department` ON `department`.`id` = `user`.`department_id`');// 手動(dòng)處理返回結(jié)果為需求結(jié)構(gòu)
該方法其實(shí)也有局限性,如果 user 和 department 不在同一個(gè)服務(wù)器是不可以連表的。
方法三:1+1查詢
該方法先查詢1次用戶列表
取出列表中的部門ID組成數(shù)組
查詢步驟2中的部門
合并最終數(shù)據(jù)
代碼大致如下:
$users = $db->query('SELECT * FROM `user`');
$departmentIds =[ ];foreach($users as $user) { if(!in_array($user['department_id'], $departmentIds)) {
$departmentIds[] = $user['department_id'];
}
}
$departments = $db->query('SELECT * FROM `department` WHERE id in ('.join(',',$department_id).')');
$map = []; // [部門ID => 部門item]foreach($departments as $department) {
$map[$department['id']] = $department;
}foreach($users as $user) {
$user['department'] = $map[$user['department_id']] ?? null;
}
該方法對(duì)兩個(gè)表沒有限制,在目前微服務(wù)盛行的情況下是比較好的一種做法。