You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL多表关联查询获取最大ID及对应关联字段的问题求助

MySQL多表关联查询获取最大ID及对应关联字段的问题求助

嗨,我现在遇到一个SQL查询的小问题,想请各位帮忙看看怎么解决:

我有三个表:connections(对应我原本说的表A)、user(表B)、depart(表C),其中connections表通过user_id和department_id关联了另外两个表的主键。我的需求是查询出connections表中最大的id,同时带上对应的用户名和部门名称,但目前得到的结果和预期不符。

先把我的表结构和相关信息贴出来:

表结构说明

  • connections表(注:我之前写错表名了,原本写成了"Table user",实际是这个关联表):
iduser_iddepartment_id
12212
22213
32214
  • user表:
iduserNameemail
22robertrob@email
  • depart表:
iddepartment
12dev
13tech
14support

我当前使用的查询语句

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)

当前得到的结果

iduserNamedepartment
3robertdev

我期望得到的结果

iduserNamedepartment
3robertsupport

有没有大佬能给我一些修改建议呀?

备注:内容来源于stack exchange,提问作者Ashu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 14:58:02