选择开始/结束日期两个表SQL

时间:2018-02-09 14:44:38

标签: php mysql

我有两个表table1和table2都包含数据和列名为timestamp

表1

| id |     name   |       timestamp     |
---------------------------------------------
|  1 |     Paul   | 2018-01-01 12:43:11 |
|  2 |     Mike   | 2018-01-07 10:13:22 |
|  3 |     Bob    | 2018-01-27 17:11:53 |
|  4 |     John   | 2018-01-15 09:08:47 |

表2

| id |     name   |       timestamp     |
---------------------------------------------
|  1 |     David  | 2018-02-01 12:43:11 |
|  2 |     Alesha | 2018-02-07 10:13:22 |
|  3 |     Smith  | 2018-03-05 17:11:53 |
|  4 |     Troy   | 2018-04-15 09:08:47 |

让我们说选择的日期是

$from = 2018-01-01 00:00:00
$to = 2018-02-08 23:59:59

如何使用一次性SQL来显示两个SQL中的所有数据? 所以请求将是

|  1 |     Paul   | 2018-01-01 12:43:11 |
|  2 |     Mike   | 2018-01-07 10:13:22 |
|  3 |     Bob    | 2018-01-27 17:11:53 |
|  4 |     John   | 2018-01-15 09:08:47 |
|  1 |     David  | 2018-02-01 12:43:11 |
|  2 |     Alesha | 2018-02-07 10:13:22 |

请注意,$ from和$ to值可能只存在于一个表中,就像

一样
$from = 2018-03-01 00:00:00
$to = 2018-03-06 23:59:59

结果将显示

|  3 |     Smith  | 2018-03-05 17:11:53 |

我尝试了这个SQL,但它不能正常工作

 SELECT * `FROM table1.table2` WHERE `timestamp` BETWEEN '$from' AND '$to'

1 个答案:

答案 0 :(得分:0)

以下内容可能有效:

(SELECT `id`, `name`, `timestamp` FROM `table1` WHERE `timestamp` BETWEEN '$from' AND '$to')
UNION
(SELECT `id`, `name`, `timestamp` FROM `table2` WHERE `timestamp` BETWEEN '$from' AND '$to')

正如您对问题的评论中所建议的那样,它使用SQL UNION命令返回两个不同SELECT语句的并集。请注意,这需要两个SELECT语句返回相同数量/类型的列。