4

我有两张桌子

USER (one row per user)

id,username,firstname,lastname,lastmodified
1,johns, John,Smith, 2009-03-01
2,andrews, Andrew,Stiller, 2009-03-03


STUDIES (multiple rows per user)

id,username,lastmodified
1,johns, 2009-01-01
1,johns, 2009-02-01
1,johns, 2009-07-01
2,andrews,2009-05-05
2,andrews,2009-04-04

我想从两个表中获取用户详细信息和最新日期:

johns,John,Smith,2009-07-01
andrews,Andrew,Stiller,2009-05-05

帮助?

4

5 回答 5

10

您需要在这里组合 MAX 和 GREATEST 函数:

select u.username
     , u.firstname
     , u.lastname
     , greatest(u.lastmodified,max(s.lastmodified))
  from USER u
     , STUDIES s
 where s.id = u.id
 group by u.id
     , u.username
     , u.firstname
     , u.lastname
     , u.lastmodified

MAX——聚合,GREATEST——最多两个值。

于 2009-11-24T13:03:42.310 回答
1

对于那些需要简单直接选择的人:

select max(lastmodified) 
from (
    select max(lastmodified) as lastmodified from USER 
    union 
    select max(lastmodified) as lastmodified from STUDIES
);

这将从 USER 获得最大日期,然后从 STUDIES 获得最大日期,然后它将返回这 2 个中的最大值。此外,您可能希望在内部选择中添加 where 子句和一些条件以改善结果。

于 2014-06-25T08:44:02.937 回答
0

像这样的东西

select username, max(lastmodified) from (
   select username, lastmodified from user 

   union all

   select username, max(lastmodified) as lastmodified 
   from studies
   group by username
) s
group by username
于 2009-11-24T13:13:01.743 回答
0
SELECT MAX(Date) FROM Users u FULL JOIN Studies s ON u.Username=s.Username GROUP BY Username
于 2009-11-24T13:11:20.750 回答
0

SELECT MAX(updatedDate) as latestUpdated FROM (SELECT updatedDate FROM audio UNION ALL SELECT updatedDate FROM videos)foo

于 2014-11-03T12:58:28.553 回答