Find unique minimum and maximum dates from 4 tables - php

I use wordpress and have 4 user tables. Each of them is as follows:

Table1 Table2 Table3 Table4 date date date date 2016-07-21 2016-11-13 2016-10-19 2016-11-18 2016-09-16 2016-10-27 2016-11-13 2016-10-25 2016-09-09 2016-09-30 2016-07-15 2016-09-28 2016-11-11 2016-08-19 2016-11-17 2016-10-24 

I need to find the minimum date of these 4 tables and the maximum date of these 4 tables. I tried to do this using the code below:

 $minViews = $wpdb->get_results(" SELECT MIN(date) as min_date FROM Table1 UNION SELECT MIN(date) as min_date FROM Table2 UNION SELECT MIN(date) as min_date FROM Table3 UNION SELECT MIN(date) as min_date FROM Table4"); $maxViews = $wpdb->get_results(" SELECT MAX(date) as max_date FROM Table1 UNION SELECT MAX(date) as max_date FROM Table2 UNION SELECT MAX(date) as max_date FROM Table3 UNION SELECT MAX(date) as max_date FROM Table4"); 

But above, the query returns each minimum and maximum date of the table. But I need to find the minimum date of all 4 tables and the maximum date of all 4 tables .

+5
source share
1 answer

You can always use a subquery in your FROM clause:

 SELECT MIN(date), MAX(date) FROM ( SELECT date FROM Table1 UNION SELECT date FROM Table2 UNION SELECT date FROM Table3 UNION SELECT date FROM Table4 ) AS sq; 
+8
source

Source: https://habr.com/ru/post/1259955/


All Articles