table
id name
1 a
2 b
3 c
4 c
5 b使用 select id, name from table group by name 可以得到不重复 name 的记录
但我现在想取得 id 靠前或者靠后的不重复记录 
期望结果如:
1 a
2 b
3 c或者
1 a
4 c
5 b简单加上 order by id 并不能实现
请教大虾如何写这条语句呢?

解决方案 »

  1.   

    select min(id),name from table group by nameselect max(id),name from table group by name
      

  2.   

    select min(id) as id,name from table group by name ordet by idselect max(id) as id,name from table group by name ordet by id
      

  3.   

    select min(id) as id,name from table group by name order by idselect max(id) as id,name from table group by name order by id
      

  4.   

    晕,不好意思,我的问题没有完全描述清楚
    结构应该是这样的
    table
    id name codeId
    1  a    a1
    2  b    b2
    3  c    c3
    4  c    c4
    5  b    b5我想取得这样的结果:
    1 a a1
    2 b b2
    3 c c3或者
    1 a a1
    4 c c4
    5 b b5就是我想把对应的max(id)或者min(id)对应的记录其他值也取出来
    select max(id) as id,name from table group by name order by id
    这条语句可以实现我在楼上描述的情况,但无法实现我这个实际的需求
    group by 出来的 id 对应的记录值,实际上并不是我要找的
    很抱歉我前面没有描述清楚
    继续请教
      

  5.   

    对于MySQL不曾用过,不知道你的MySQL版本支持不支持子查询。select t.* from tname t where not exists(select 1 from tname where name=t.name and id<t.id)select t.* from tname t where not exists(select 1 from tname where name=t.name and id>t.id)
      

  6.   

    select t.* from tname t where t.id=(select min(id) from tname where name=t.name)select t.* from tname t where t.id=(select max(id) from tname where name=t.name)
      

  7.   

    --取出表中name相同且不存在id比当前记录id更小的其他记录。select t.* from tname t where not exists(select 1 from tname where name=t.name and id<t.id)
    --取出表中name相同的记录中id最小的那一条。select t.* from tname t where t.id=(select min(id) from tname where name=t.name)