有两个表T1(c1, c2)和T2(c1, c3, c4)。
其中,T1里c1是主键,T2里三个字段合起来是主键。现在要做一个这样的查询,对于T1里的每一个c1值,查出T2里c1=T1.c1的记录中c3最大的那条记录。举个例子:
T1的内容是:
c1    |c2
c1v1  |c2v1
c1v2  |c2v2T2的内容是:
c1    |c3    |c4
c1v1  |1     |c4v1
c1v1  |2     |c4v2
c1v2  |4     |c4v3
c1v1  |5     |c4v4
c1v2  |3     |c4v2那么查出来的结果应该是:
T1.c1    |T2.c3
c1v1     |5
c1v2     |4请问这样的SQL语句该怎么写呢?

解决方案 »

  1.   

    select c1,c3
    from t2 a
    where not exists (select 1 from t2 where c1=a.c1 and c4>a.c4)
      

  2.   

    SELECT * from t1 a inner join t2 b on a.c1=b.c1
    where not exists(select 1 from t2 where c3>b.c3 and c1=b.c1)
      

  3.   

    or
    SELECT a.c1,max(b.c3) from t1 a inner join t2 b on a.c1=b.c1 group by a.c1
      

  4.   

    select c1,max(c3) from t2 group by c1;
      

  5.   

    not exists中的t2和join之后的不是同一个.