-
首先重温一下左连接 以左表为基础,根据ON后给出的两表的条件将两表连接起来。结果会将左表所有的查询信息列出,而右表只列出ON后条件与左表满足的部分。左连接全称为左外连接,是外连接的一种。 -
数据库关系 notice表中存的publisher字段是发布人的id notice表中存的publish_organ字段是发布人单位的id 现在要写个sql通过id查询到对应的用户姓名和用户单位。用户表为sys_user,部门表为sys_depart SELECT n.id, n.title, n.content, n.lng, n.lat, n.publish_time, n.show_title, n.file_name, n.file_path, n.create_by, n.create_time,
d.depart_name as publish_organ, u.realname as publisher
from l_notice n LEFT JOIN sys_user u on u.id = n.publisher
LEFT JOIN sys_depart d on d.id = n.publish_organ ORDER BY create_time DESC LIMIT 5;
查询结果 3. sql有了现在将其写入程序
NoticeMapper中新建接口,将sql写入程序。
@Mapper
public interface NoticeMapper extends BaseMapper<NoticeEntity> {
@Select("SELECT n.id, n.title, n.content, n.lng, n.lat, n.publish_time, n.show_title, n.file_name, n.file_path, n.create_by, n.create_time, \n" +
"d.depart_name as publish_organ, u.realname as publisher \n" +
"from l_notice n LEFT JOIN sys_user u on u.id = n.publisher \n" +
"LEFT JOIN sys_depart d on d.id = n.publish_organ ORDER BY create_time DESC LIMIT #{limit}")
List<NoticeEntity> selectLastNum(@Param("limit") Integer limit);
}
- service层加入接口,实现方法。
public interface INoticeService extends IService<NoticeEntity> {
List<NoticeEntity> getLastNotices(Integer limit);
}
实现方法
@Service("noticeService")
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, NoticeEntity> implements INoticeService {
@Override
public List<NoticeEntity> getLastNotices(Integer limit) {
return getBaseMapper().selectLastNum(limit);
}
}
controller层
List<NoticeEntity> noticeEntityList = noticeService.getLastNotices(5);
|