例如用户表
user_id | user_name |
1 | zhangsan |
2 | lisi |
3 | wangwu |
4 | zhaoliu |
另一张money表,表示了借钱的关系
id | from | to | how |
1 | 1 | 2 | 100 |
2 | 3 | 4 | 100 |
关联查询
select m.id,u1.user_name,u2.user_name,m.how
from money as m
left outer join user u1 on u2.user_id=m.from
left outer join user u3 on u3.user_id=m.to
显示的结果为
id | user_name | user_name | how |
1 | zhangsan | lisi | 100 |
2 | wangwu | zhaoliu | 100 |
这里有个小问题,中间两列显示的名称一样,都是user_name,这样就不好辨别了,在Mybatis中如果想用
@ResultType(实体类名称.class)
来定义返回的类型,因为两个字段名一样,定义的实体类肯定不能一样,就会导致返回没有结果,怎么处理呢?
关联查询时,指定结果字段别名
select m.id,u1.user_name as user_name1,u2.user_name as user_name2,m.how
from money as m
left outer join user u1 on u2.user_id=m.from
left outer join user u3 on u3.user_id=m.to