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

标签 php mysql

我有这张 table

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

最佳答案

你可以在 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;

关于php - 如何获取组之间的第一条和最后一条记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33982009/

相关文章:

mysql - sql 查询没有返回足够的行

php - 如何使用准备好的语句插入多行

javascript - 使用 javascript 监控 twilio 调用

php.ini max_upload_file 大小回落到默认 2M

php - 我需要使用 html 中的 select 发送 id

php - MYSql 准备不接受我的请求 : No tables used

Java:在MySQL中高效存储Protobuf对象

php - 递归嵌套对象

java - 如何将 gps 坐标存储在 mysql 数据库中?

javascript - 阻止了原点的帧如何修复