多表查询时是联表查询好还是单表分步查询比较好

进行后台数据查询的时候经常会有联表查询的情况,联表查询的时候判断是联表查询比较好还是单表分步查询比较好的条件如下:

可以用join,因为被驱动表t_area的area_code是主键索引,会用Index Nested-Loop Join这个算法,效率比较高

你可以把sql前面加EXPLAIN 在客户端上运行一下

没出现Block Nested Loop这个就可以用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. 创建 Employee 实体类和 Department 实体类,分别对应员工表和部门表的结构。 Employee.java ``` public class Employee { private int id; private String name; private int age; private int departmentId; // getter/setter 省略 } ``` Department.java ``` public class Department { private int id; private String name; // getter/setter 省略 } ``` 2. 创建 EmployeeMapper 接口和 DepartmentMapper 接口,用于定义查询方法。 EmployeeMapper.java ``` public interface EmployeeMapper { // 根据员工 id 查询员工信息 Employee selectEmployeeById(int id); // 根据部门 id 查询部门信息 Department selectDepartmentById(int id); } ``` DepartmentMapper.java ``` public interface DepartmentMapper { // 根据部门 id 查询部门信息 Department selectDepartmentById(int id); } ``` 3. 创建 EmployeeMapper.xml 和 DepartmentMapper.xml 文件,用于实现查询方法。 EmployeeMapper.xml ``` <?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.example.mapper.EmployeeMapper"> <select id="selectEmployeeById" parameterType="int" resultType="com.example.entity.Employee"> SELECT * FROM employee WHERE id = #{id} </select> <select id="selectDepartmentById" parameterType="int" resultType="com.example.entity.Department"> SELECT * FROM department WHERE id = #{id} </select> </mapper> ``` DepartmentMapper.xml ``` <?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.example.mapper.DepartmentMapper"> <select id="selectDepartmentById" parameterType="int" resultType="com.example.entity.Department"> SELECT * FROM department WHERE id = #{id} </select> </mapper> ``` 4. 在配置文件中配置 mapper。 ``` <configuration> <mappers> <mapper resource="com/example/mapper/EmployeeMapper.xml"/> <mapper resource="com/example/mapper/DepartmentMapper.xml"/> </mappers> </configuration> ``` 5. 在业务代码中使用分步查询。 ``` @Autowired private EmployeeMapper employeeMapper; @Autowired private DepartmentMapper departmentMapper; public Employee getEmployeeById(int id) { Employee employee = employeeMapper.selectEmployeeById(id); Department department = departmentMapper.selectDepartmentById(employee.getDepartmentId()); employee.setDepartment(department); return employee; } ``` 以上是使用 MyBatis 实现分步查询的步骤和代码示例,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晒干的老咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值