MySql语句查询。请问大家,如下图。怎样从每个cat_id中取出最大和次最大的goods_id?谢谢!

 我来答
tjrmgs
推荐于2016-03-26 · TA获得超过5767个赞
知道大有可为答主
回答量:2161
采纳率:94%
帮助的人:1121万
展开全部

这个事情比较麻烦。为了简化SQL语句,这里只输出cat_id、最大goods_id和次最大goods_id并且假设表名是tbl

select t1.cat_id,t1.maxGid,t2.maxScndGid from 
(select cat_id,max(goods_id) as maxGid from tbl group by cat_id)t1 
left join 
(select t.cat_id,max(t.goods_id) as maxScndGid from 
(select cat_id,goods_id from tbl a where not exists
(select 1 from (select cat_id,max(goods_id) as maxgid from tbl group by cat_id) b 
where b.cat_id=a.cat_id and b.maxgid=a.goods_id))t 
group by t.cat_id)t2 
on t1.cat_id=t2.cat_id


上述语句中的子查询t2负责查出每个cat_id 的次最大goods_id。它使用了not exists,碰到大数据表的情况下,在有可被利用的索引时其运行效率是很高的,反之其运行效率会很低,这种情况下建议改为内连接来提高查询速度。


如果需要同时输出goods_name,则需要再增加一个唯一的goods_id和goods_name对照表实施连接,语句将更加复杂。

追问
刚接触数据库,实在是不太明白。顺便问一下,Oracle中建表时怎样给列设置默认值,就像MySQL中,如:id int not null default 0;
追答
oracle 设置字段默认值的方法跟mySql相同。例如:
create table test (iid int not null default 0); --创建表时指定默认值

alter table test modify id default 1; --修改默认值
alter table students modify sex default null; --删除默认值
创作者BbPV9CfuDM
2014-11-17 · TA获得超过1445个赞
知道小有建树答主
回答量:977
采纳率:85%
帮助的人:202万
展开全部
select * from table order by goods_id desc limit 2;
追问
是求各个cat_id中的最大和次最大goods_id
追答
select a.* from table a,table b where a.cat_id = b.cat_id and a.goods_id>b.goods_id;
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式