合并两个具有不同结构

时间:2017-12-18 13:50:26

标签: mysql sql

我有两张桌子:

事件

CREATE TABLE IF NOT EXISTS `event` (
          `eventId` bigint(20) NOT NULL AUTO_INCREMENT,
          `eventTime` bigint(20) NOT NULL COMMENT 'ex: 1431201865000 (epoch is milliseconds)',
          `sourceId` bigint(20) NOT NULL COMMENT 'ex: pole-code: 1 = JA005, patrolCarCode: 5000 = D4588',
          `plateNumber` varchar(40) COLLATE utf8_unicode_ci NOT NULL COMMENT 'ex: 5849',
          `plateGps` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'ex: 0.000000 N  0.000000 E') 
    ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

来源

CREATE TABLE IF NOT EXISTS `source` (
  `sourceId` bigint(20) NOT NULL AUTO_INCREMENT,
  `sourceName` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT 'ex: pole-code: JA005, patrolCarCode:D4588',
  `sourceSimIp` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'ex: 192.55.44.22',
  `sourceGps` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Only for Fixed source (Poles) ex: 25.110227 N  55.239798 E, 24.993183 N  55.250382 E, 0.000000 N  0.000000 E',
  PRIMARY KEY (`sourceId`),
  KEY `sourceName` (`sourceName`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

示例数据

INSERT INTO `source` (`sourceId`, `sourceName`, `sourceSimIp`, `sourceGps`) VALUES
    (1, 'Pole 1', '74.200.230.71', '7.8731 N  80.7718 E'),
    (2, 'Car 1', '40.214.203.72', '')


INSERT INTO `event` (`eventId`, `eventTime`, `sourceId`, `plateNumber`, `plateGps`) 
VALUES
    (1, 1498806550534, 1, '1111', null),
    (2, 1498806550544, 2, '1111', '7.2936 N 80.6413 E'),
    (3, 1498806550554, 2, '1111', '7.9570 N 80.7601 E'),
    (4, 1498806550564, 2, '1112', '7.9580 N 80.7601 E'),
    (5, 1498806550584, 1, '1111', null),
    (6, 1498806550574, 1, '1111', '7.3010 N 80.3872 E')

问题:

有两种类型的来源。  1.静电源(POLE CAMERA)  2.动态源(MOVING CAR CAMERA)

在事件表中,如果新条目来自静态源,我们已经将GPS值保存在源表中,因此我们只保存源ID并保持plateGPS字段为空,但对于动态源我们没有GPS值在源表中因为源是动态的,并且每个事件都有不同的位置,这些位置保存在事件表的plateGps字段中,并且源Id指向源表(仅供参考)。

现在我需要构建一个查询,其中用户将指定'PlateNumber',我需要按事件顺序检查我们系统中的所有GPS事件。

静态源和动态源可以检测到一个PlateNumber,因此我正在寻找动态方法来从两者中获取GPS事件。

我能够创建以下查询,但它没有按照事件时间限制来处理顺序。

select source.sourceGps  as 'sourceGps' from source where source.sourceId in (select event.sourceId   from event  where eventTime >= 1488312001000 and eventTime <= 1513886399000 and event.plateNumber = '1111' and plateGps is null) 
 union all 
select plateGps as 'sourceGps'  from event  where eventTime >= 1488312001000 and eventTime <= 1513886399000  and event.plateNumber = '1111' and length(plateGps) > 0 

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

也许您需要left join order by

select coalesce(s.sourceGps, e.plateGps) as sourceGps, 
from event e left join
     source s
     on s.sourceId = e.sourceId  
where e.eventTime >= 1488312001000 and e.eventTime <= 1513886399000 and
      e.plateNumber = '5327'
order by e.eventTime;