MySQL多表关联查询获取最大ID及对应关联字段的问题求助
MySQL多表关联查询获取最大ID及对应关联字段的问题求助
嗨,我现在遇到一个SQL查询的小问题,想请各位帮忙看看怎么解决:
我有三个表:connections(对应我原本说的表A)、user(表B)、depart(表C),其中connections表通过user_id和department_id关联了另外两个表的主键。我的需求是查询出connections表中最大的id,同时带上对应的用户名和部门名称,但目前得到的结果和预期不符。
先把我的表结构和相关信息贴出来:
表结构说明
connections表(注:我之前写错表名了,原本写成了"Table user",实际是这个关联表):
| id | user_id | department_id |
|---|---|---|
| 1 | 22 | 12 |
| 2 | 22 | 13 |
| 3 | 22 | 14 |
user表:
| id | userName | |
|---|---|---|
| 22 | robert | rob@email |
depart表:
| id | department |
|---|---|
| 12 | dev |
| 13 | tech |
| 14 | support |
我当前使用的查询语句
select max(c.id), c.user_id, u.userName, d.department from connections c INNER JOIN user u ON c.user_id = u.id INNER JOIN depart d ON c.department_id = d.id GROUP BY c.user_id
(注:这里我还修正了字段名的笔误,原语句里的departmen_id少了个t,应该是department_id)
当前得到的结果
| id | userName | department |
|---|---|---|
| 3 | robert | dev |
我期望得到的结果
| id | userName | department |
|---|---|---|
| 3 | robert | support |
有没有大佬能给我一些修改建议呀?
备注:内容来源于stack exchange,提问作者Ashu
相关产品推荐
相关产品推荐

