Select start/end dates two tables SQL

65 views Asked by At

I have two tables table1 and table2 in both contains data and column named timestamp

table1

| 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 |

table2

| 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 |

Lets say the selected date are

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

How to make a one time SQL to show the all data in both SQL ? So the request would be

|  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 |

Please note the $from and $to values could exist in one table only like if

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

Result will show

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

I tried this SQL but its not working

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

There are 1 answers

0
ngj On

Something like the following might work:

(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')

As suggested in the comments to your question, this uses the SQL UNION command to return the union of two different SELECT statements. Note that this requires both SELECT statements to return the same number/types of columns.