基于上一个和下一个值的mysql查询

时间:2018-04-18 05:40:36

标签: mysql sql mysqli phpmyadmin mysql-workbench

我有以下表test1

-- auto-generated definition
CREATE TABLE test1
(
  imei     VARCHAR(10) DEFAULT '1'             NULL,
  id       INT(6) UNSIGNED AUTO_INCREMENT
    PRIMARY KEY,
  lat      FLOAT(10, 5)                        NOT NULL,
  lng      FLOAT(10, 5)                        NOT NULL,
  ign      CHAR                                NULL,
  datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP
)
  ENGINE = InnoDB;

以下数据

INSERT INTO test1 (imei, id, lat, lng, ign, datetime) VALUES ('1', 1, 27.1, 28.2, '0', '2018-04-18 02:15:25');
INSERT INTO test1 (imei, id, lat, lng, ign, datetime) VALUES ('1', 2, 27.2, 28.2, '1', '2018-04-18 02:16:59');
INSERT INTO test1 (imei, id, lat, lng, ign, datetime) VALUES ('1', 3, 27.3, 28.4, '1', '2018-04-18 02:17:59');
INSERT INTO test1 (imei, id, lat, lng, ign, datetime) VALUES ('1', 4, 27.4, 28.5, '0', '2018-04-18 02:18:59');
INSERT INTO test1 (imei, id, lat, lng, ign, datetime) VALUES ('1', 1, 27.1, 28.2, '0', '2018-04-18 02:25:25');
INSERT INTO test1 (imei, id, lat, lng, ign, datetime) VALUES ('1', 2, 27.2, 28.2, '1', '2018-04-18 02:26:59');
INSERT INTO test1 (imei, id, lat, lng, ign, datetime) VALUES ('1', 3, 27.3, 28.4, '1', '2018-04-18 02:27:59');
INSERT INTO test1 (imei, id, lat, lng, ign, datetime) VALUES ('1', 4, 27.4, 28.5, '0', '2018-04-18 02:28:59');

逻辑在这里:

  1. 首先它将检查ign列;如果该值为1(表示点火开启),那么它将生成第一部分:imei lat lng status datetime

  2. 然后查询需要选择第二部分:如果值为0(点火关闭),它将检查ign列,然后它将生成第二部分:imei lat lng status datetime

  3. 我试过这个查询

    SELECT test1.imei, test1.lat, test1.lng ,
    MAX(CASE WHEN test1.ign = 1 THEN 'ign on' END) as IgnOn,
    min(CASE WHEN test1.ign = 0 THEN 'ign of' END) as IgnOff
    FROM test1 GROUP BY test1.imei, test1.lat, test1.lng;
    

    经过多次搜索后我才能创建此查询

    select *,
      if(test1.ign = 1, 'ign on', 'ign off') as status,
      CASE
      WHEN test1.ign = 1 THEN @a := 0
        ELSE @a := 1
      END as mycondition
    from test1
     WHERE test1.imei = 1
      HAVING test1.ign = @a
      ORDER BY reg_date ASC;
    

    这是我需要的结果:

    imei    i1lat    i1lng    i1status         i0datetime           i0lat    ign1lng    i1status    i1datetime
      1      27.2     28.2       1          2018-04-18 02:16:59      27.4      28.5       0         2018-04-18 02:18:59
      1      27.2     28.2       1          2018-04-18 02:26:59      27.4      28.5       0         2018-04-18 02:28:59
    

    我可以编写一个php脚本来生成我想要的数据,但我想用mysql生成相同的数据。

1 个答案:

答案 0 :(得分:0)

select *,
  if(test1.ign = 1, 'ign on', 'ign off') as status,
  CASE
  WHEN test1.ign = 1 THEN @a := 0
    ELSE @a := 1
  END as mycondition
from test1
 WHERE test1.imei = 1
  HAVING test1.ign = @a
  ORDER BY reg_date ASC;