如何获取组之间的第一个和最后一个记录?

时间:2015-11-29 10:58:37

标签: php mysql

我有这张桌子

CREATE TABLE test (id INT, on_off  TINYINT NOT NULL);
INSERT INTO test
(id,n_off) VALUES
(12,1),
(13,1),
(14,1),
(15,0),
(16,0),
(17,0),
(18,0),
(19,1),
(20,1),
(21,1),
(22,1),
(22,0),
(23,0),
(24,1),
(25,1),
(26,1);

如何获得第一组和最后一条组,就像每个组一样 使用mysql和php

min_id   max_id   on_off
12         14      1
19         22      1
24         26      1

或者

id   on_off
12     1
14     1

20     1
22     1

24     1
26     1

1 个答案:

答案 0 :(得分:1)

您可以在MySQL中执行此操作:

set @c=0;
SELECT
    if (@prev != test.on_off,@c:=@c+1,@c) as `tmp`,
    min(id) as min_id,max(id) as max_id, @prev := test.on_off  as  on_off
from test,
    (
        select @prev := -1
    ) as i
group by `tmp`
order by test.id;

如果您只需要值为1的行,则:

set @c=0;
select min_id, max_id,on_off  from
  (SELECT
      if (@prev != test.on_off,@c:=@c+1,@c) as `tmp`,
      min(id) as min_id,max(id) as max_id, @prev := test.on_off  as  on_off
  from test,
      (
          select @prev := -1
      ) as i
  group by `tmp`
  order by test.id) as `t`
where on_off = 1;