求一个sql

yyz0832 2010-03-12 05:39:07
insert into student(name,classid) values
(1,'yuan',1),
(2,'yuanyongzhi',1),
(3,'zhang',2),
(4,'zhangsan',2),
(5,'lisi',3),
(6,'wangwu',4)

想要的结果 即如果classid相同,取ID最大的
+----+-------------+---------+
| id | name | classid |
+----+-------------+---------+
| 6 | wangwu | 4 |
| 5 | lisi | 3 |
| 4 | zhangsan | 2 |
| 2 | yuanyongzhi | 1 |
+----+-------------+---------+
...全文
111 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
vipper23 2010-03-15
  • 打赏
  • 举报
回复
mysql> select * from student a where not exists (select 1 from student where classid=
-> a.classid and id>a.id) order by id desc;
+------+-------------+---------+
| id | name | classid |
+------+-------------+---------+
| 6 | wangwu | 4 |
| 5 | lisi | 3 |
| 4 | zhangsan | 2 |
| 2 | yuanyongzhi | 1 |
+------+-------------+---------+
geneshell 2010-03-15
  • 打赏
  • 举报
回复
我用的是MySQL 5,SQL如下,已经测试过,没问题,:D

select max(id), name, classid from student group by classid
wwwwb 2010-03-15
  • 打赏
  • 举报
回复
SELECT a.id,a.name,a.classid FROM t2v a
LEFT JOIN t2v b
ON a.classid=b.classid AND a.id <=b.id
GROUP BY a.id,a.name,a.classid
HAVING COUNT(b.id) <=3


SELECT a.id,a.name,a.classid FROM t2v a
WHERE 3>=(
SELECT COUNT(*) FROM t2v b
WHERE a.classid=b.classid AND a.id <=b.id)


zxcvbnmluton 2010-03-15
  • 打赏
  • 举报
回复
上面数据库表名写错了

select max(id) as id,name,classid from student order by classid desc
zxcvbnmluton 2010-03-15
  • 打赏
  • 举报
回复
select max(id) as id,name,classid from tb order by classid desc
百年树人 2010-03-13
  • 打赏
  • 举报
回复
select *
from student s
where not exists(select 1 from student where classid=s.classid and id>s.id)
my_caterpillar 2010-03-13
  • 打赏
  • 举报
回复
也想去看看这样的文件哈!谢喽!
ACMAIN_CHM 2010-03-12
  • 打赏
  • 举报
回复
参考下贴中的例子,及N=1时的方法。

[征集]分组取最大N条记录方法征集
http://topic.csdn.net/u/20091231/16/2f268740-391e-40f2-a15e-f243b2c925ab.html
阿_布 2010-03-12
  • 打赏
  • 举报
回复
select * from student t where not exists(select 1 from student where classid=t.classid and id>t.id);
yyz0832 2010-03-12
  • 打赏
  • 举报
回复
插入语句写错了
insert into student(id,name,classid) values
(1,'yuan',1),
(2,'yuanyongzhi',1),
(3,'zhang',2),
(4,'zhangsan',2),
(5,'lisi',3),
(6,'wangwu',4)

56,679

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧