获取分组的前几组方法

获取分组的前几组方法。


/*Table structure for table `t` */

DROP TABLE IF EXISTS `t`;

CREATE TABLE `t` (
  `id` int(11) NOT NULL auto_increment,
  `g_id` int(11) NOT NULL,
  `t_str` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  key (`g_id`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;

/*Data for the table `t` */

insert into `t`(`id`,`g_id`,`t_str`) values
(1,2,'wo'),
(2,2,'ni'),
(3,2,'ta'),
(4,3,'wo '),
(5,4,'ni'),
(6,3,'ni'),
(7,4,'ta'),
(8,3,'wang'),
(9,4,'li'),
(10,3,'hai'),
(11,4,'ri'),
(12,2,'ren'),
(13,5,'ta'),
(14,6,'ri'),
(15,6,'ren'),
(16,6,'fuck'),
(17,6,'shit'),
(18,5,'ls'),
(19,5,'chmod'),
(20,5,'chgrp'),
(21,5,'chown'),
(22,3,'rm'),
(23,3,'desc'),
(24,4,'pwd'),
(25,5,'cd');
1、相关子查询
(这个SQL语句是从ITPUB上来的。)
select a.* from t a where
(
select count(*) from t b where a.g_id = b.g_id and b.id<a.id
) < 2 order by a.g_id desc;

2、存储过程。
DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`sp_get_num_group`$$

CREATE PROCEDURE `test`.`sp_get_num_group`(
 IN f_num int)
BEGIN
  -- The variable stands for totla number of the record.
  declare cnt int default 0;
  declare i int;
  -- Create temp table to reserved the result.
  create temporary table if not exists tmp select * from t where 1 = 0;
  -- Get the total number of the group by record.
  select count(*) from
  (
    select count(*) from t group by g_id order by null
  ) T into cnt;
  set i = 0;
  while i < cnt
  do
    -- Get the real g_id one by one.
    set @stmt = concat('select g_id from t group by g_id order by g_id desc limit ',i,',1 into @tmp_id');
    prepare s1 from @stmt;
    execute s1;
    drop prepare s1;
    set @stmt = '';
    -- Get the needed data.
    set @stmt = concat('insert into tmp select * from t where g_id = ',@tmp_id,' limit ',f_num);
    prepare s1 from @stmt;
    execute s1;
    drop prepare s1;
    set @stmt = '';
    set @tmp_id = 0;
    set i = i + 1;
  end while;
  -- Get the record from temp table.
  select * from tmp order by g_id desc,id desc;
  -- Drop temp table.
  drop table tmp;
END$$

DELIMITER ;

本文出自 “上帝,咱们不见不散!” 博客,转载请与作者联系!

转载于:https://my.oschina.net/u/585111/blog/219491

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值