用表举例
表A(id,a两个字段):
id   a
1 a
2 b
3 c
4 d表B(x,y两个字段)
x  y
a  1
a  2
c  3
b  4x的外键为a,现在我想选择数据,要求是对表A的a字段分组,同时选择出表B中X相同情况下Y较大的值, select * from A,B group by a,这样出来的显示的Y项一般是1,我如何能让结果显示2?
 

解决方案 »

  1.   

    select a.id,b.x,max(b.y) maxval from A join B on A.a=B.x group by a.id,b.x
      

  2.   

    不好意思,描述错误了,表B应该是这样的
    x  y   z
    a  1   算法
    a  2   阿飞
    c  3   撒旦发生
    b  4   阿斯发选的是Y的最大值,但是数据是Z字段的
      

  3.   

    select A.a,S.z 
      from A,(select x,z from B b1 where y = (select max(y) from B b2 where b2.x = b1.x)) S
     where A.a = S.x 
     group by A.a,S.z;
      

  4.   

    已解决,谢谢楼上的启发
    select X.id,X.soid,Z.type_describe,X.current_status,X.re as R1,X.create_time,Y.re as R2,U.cname from tb_event X left join (select event_id,re from tb_event_details y1 where id=(select max(id) from tb_event_details y2 where y2.event_id=y1.event_id)) Y on X.id=Y.event_id,tb_event_type Z,usr U  where  X.event_type=Z.id and X.create_usr=U.usr_id and current_status=0 order by create_time desc limit 0,50