我正在使用wordpress并有4个自定义表。他们每个人都是这样的:
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
我需要找到这4个表的最小日期和这4个表的最大日期。我尝试通过下面的代码来做到这一点:
$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");
但是上面的查询返回每个表的最小和最大日期。但我需要找到所有4个表的最短日期和所有4个表的最长日期。
答案 0 :(得分:8)
您始终可以在FROM子句中使用子查询:
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;