
MySql语句查询。请问大家,如下图。怎样从每个cat_id中取出最大和次最大的goods_id?谢谢!
2个回答
展开全部
这个事情比较麻烦。为了简化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; --删除默认值
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询