MySQL - 如何加入/联合这两个选择来进行单个查询?

时间:2014-07-16 20:19:49

标签: mysql join relational-database union

我的数据库上有以下表格:

CREATE TABLE IF NOT EXISTS `heartbeat` (
  `code` int(11) NOT NULL AUTO_INCREMENT,
  `IMEI` varchar(15) NOT NULL,
  `oil_electricity` tinyint(1) NOT NULL,
  `gps_tracking` tinyint(1) NOT NULL,
  `alarm_status` tinyint(3) NOT NULL,
  `charge` tinyint(1) NOT NULL,
  `ACC` tinyint(1) NOT NULL,
  `defense` tinyint(1) NOT NULL,
  `voltage_level` tinyint(1) unsigned NOT NULL,
  `gsm_signal` tinyint(1) unsigned NOT NULL,
  `alarm` tinyint(1) NOT NULL,
  `language` tinyint(1) NOT NULL,
  `datetime` datetime NOT NULL,
  PRIMARY KEY (`codigo`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1451 ;

我有两个选择,我需要将结果作为一个单一查询语句连接在一起:

SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime`<="2014-07-16 12:00"
SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime` BETWEEN "2014-07-16 12:00" AND "2014-07-17 15:00"

我尝试了以下但是没有用:

SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime`<="2014-07-16 12:00" JOIN (SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime` BETWEEN "2014-07-16 12:00" AND "2014-07-17 15:00")
or
SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime`<="2014-07-16 12:00" UNION (SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime` BETWEEN "2014-07-16 12:00" AND "2014-07-17 15:00")

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

在sql中有一个UNION结构,如下所示:

SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime`<="2014-07-16 12:00" JOIN (SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime` BETWEEN "2014-07-16 12:00" AND "2014-07-17 15:00")
UNION
SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime`<="2014-07-16 12:00" UNION (SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime` BETWEEN "2014-07-16 12:00" AND "2014-07-17 15:00")

文档可在此处找到:

http://dev.mysql.com/doc/refman/5.0/en/union.html

答案 1 :(得分:1)

在你的create语句中你遇到了主键的问题我假设这只是一个错字,应该是'code'。至于问题我不清楚你是否必须使用连接或联合,或者你只需​​要结果,这两个查询只会产生一个查询。如果后者是这种情况,则应该有效:

SELECT * FROM heartbeat
WHERE IMEI='123456789012345' AND datetime <= '2014-07-17 15:00';

我对单日期声明的推理如下:您正在寻找小于或等于2014年7月16日12:00在2014年7月16日12:00至2014年7月17日15:00在第二天这将是截至2014年7月17日的一切。

答案 2 :(得分:0)

好的,只需稍加改动即可。

很抱歉打扰这么简单的问题。

SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime`<="2014-07-16 12:00" ORDER BY `code` desc LIMIT 1 
UNION
SELECT * FROM heartbeat WHERE `IMEI`=123456789012345 AND `datetime` BETWEEN "2014-07-16 12:00" AND "2014-07-17 15:00"

编辑:将ORDER BY code desc LIMIT 1添加到第一个查询