mysql怎么写,根据 a 表的 id 查出 b 表中对应id 最大的count 聚合后返回

======= a 表
id|a|b
1| 2 3|

2| 2 3|

======= b表
id|count|f
1| 2 | 0
1| 3 | 1
2| 2 | 0

2| 3 | 1

===== 结果
id| a |b| count | f
1 2 3 3 1

2 2 3 3 1

根据 a 表的 id 查出 b 表中对应id 最大的count 聚合后返回

结果 包含 a 表 所有字段 和 b表 最大 count 数据 的所有 字段

这个mysql怎么写

阅读 2.8k
3 个回答
建议:把建表语句和测试用例发出来

建表:

create table a(id int,a int,b int);
create table b(id int,count int,f int);

测试用例:

insert into a values(1,2,3),(2,2,3),(3,1,1);
insert into b values(1,2,0),(1,3,1),(2,2,0),(2,3,1);

用上面的测试用例,下面的sql可以达到你的要求

select a.*,b1.`count`,b1.f
 from b b1 
  inner join (
    select b.id,max(b.`count`) max_cnt
     from b
      inner join a on a.id=b.id
     group by b.id
   )b2 on b1.id=b2.id and b1.`count`=b2.max_cnt 
  right join a on a.id=b1.id;

结果:

+------+------+------+-------+------+
| id   | a    | b    | count | f    |
+------+------+------+-------+------+
|    1 |    2 |    3 |     3 |    1 |
|    2 |    2 |    3 |     3 |    1 |
|    3 |    1 |    1 |  NULL | NULL |
+------+------+------+-------+------+

但要是b表多加

insert into b values(1,3,2);

结果就不满足了,还得再改进下

select a.id,a.a,a.b,b1.`count`,max(f) f
 from b b1 
  inner join (
    select b.id,max(b.`count`) max_cnt
     from b
      inner join a on a.id=b.id
     group by b.id
   )b2 on b1.id=b2.id and b1.`count`=b2.max_cnt 
  right join a on a.id=b1.id
 group by a.id,a.a,a.b,b1.`count`;

两个表通过id INNER JOIN就行了:

SELECT a.id,a,b,count,f FROM a INNER JOIN b ON a.id = b.id ORDER BY count LIMIT 1;
SELECT a.id,a,b,count,f FROM a INNER JOIN b ON a.id = b.id ORDER BY count desc LIMIT 1;

select a.id,a.a,a.b,b.count ,b.f from a a
left join b b on a.id=b.id 
where b.count=(select max(count) from b where id=a.id)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题