mysql查询

g9icjywg  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(358)

我有下表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');

逻辑如下:
首先它会检查 ign 列;如果值为1(表示点火开关打开),则会生成第一部分: imei lat lng status datetime 然后查询需要选择第二部分:它将检查 ign 列如果值为0(点火关闭),则它将生成第二部分: imei lat lng status datetime 我试过这个问题

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生成相同的数据。

57hvy0tb

57hvy0tb1#

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;

相关问题