跨表的列中获取最大的公共值

时间:2015-04-02 20:35:52

标签: mysql sql

我有4个表格(比如A,B,C和D),所有这些表都带有' date'。我需要在所有四个表中找到最大的公共日期值。也就是说,所有四个表中存在的最大日期值。我怎么能这样做?

目前,我正在查找所有四个表的MAX日期值的MIN,但是如果MIN存在于一个表中但不存在于第二个表中,则会失败。

这是一个让事情更清晰的例子:

A.date
------
2015-03-31
2015-03-30
2015-03-29
2015-03-27

B.date
------
2015-03-30
2015-03-29
2015-03-28
2015-03-27

C.date
------
2015-03-29
2015-03-27
2015-03-26
2015-03-25

D.date
------
2015-03-28
2015-03-27
2015-03-26
2015-03-25

我为找到最高共同日期所做的是:

SELECT MIN(max_date) FROM (
SELECT MAX(date) AS max_date FROM A
UNION
SELECT MAX(date) AS max_date FROM B
UNION
SELECT MAX(date) AS max_date FROM C
UNION
SELECT MAX(date) AS max_date FROM D
) T;

这给了我2015-03-28,但后来我意识到有些表可能没有这个日期。我真正想要的日期是2015-03-27。

2 个答案:

答案 0 :(得分:3)

这是一种方法:

select date
from (select date, 'a' as which from a union all
      select date, 'b' as which from b union all
      select date, 'c' as which from c union all
      select date, 'd' as which from d
     ) x
group by date
having count(distinct which) = 4
order by date desc
limit 1;

以下版本可能会更好一些,特别是如果每​​个表中的date都有索引:

select date
from (select distinct date, 'a' as which from a union all
      select distinct date, 'b' as which from b union all
      select distinct date, 'c' as which from c union all
      select distinct date, 'd' as which from d
     ) x
group by date
having count(*) = 4
order by date desc
limit 1;

答案 1 :(得分:1)

您需要在4个单独的表中获得所有日期值的交集。然后,选择这些值的MAX

SELECT MAX(date)
FROM A
WHERE date IN (
  SELECT date 
  FROM B
  WHERE date IN (
     SELECT date
     FROM C
     WHERE date IN (
        SELECT date
        FROM D)))

SQL Fiddle Demo here