3

更新 - 问题

除了使用自联接之外,是否有更紧凑的方法来编写从表中选择最大记录的查询?

例如,可能具有以下架构的事件表:

   EventID | EventType | Timestamp | Description
-----------+-----------+-----------+--------------
   INT     | VARCHAR   | INT       | VARCHAR

并且可能包含每种事件类型的多条记录。比方说:

     1     |    A      |  100000   | 'First Event'
     2     |    A      |  100005   | 'Second Event'
     3     |    B      |  100009   | 'Third Event'
     4     |    A      |  100009   | 'Fourth Event'
     5     |    B      |  100010   | 'Fifth Event'
     6     |    B      |  100030   | 'Sixth Event'
     7     |    A      |  100030   | ' ... '
     8     |    C      |  100030   | ' ... '
     9     |    C      |  100050   | ' ... '

假设我想知道每种类型的最新事件是什么——事件#6、#7 和#9。然后我必须编写一个如下所示的查询:

SELECT EventID
     , EventType
     , Timestamp
     , Description
  FROM EventsTable T
 INNER JOIN (SELECT EventType
                  , MAX(Timestamp) 
               FROM EventsTable TInner
              GROUP BY EventType) TSelf
         ON T.Timestamp = TSelf.Timestamp
         AND T.EventType = TSelf.EventType

所以问题归结为:是否有更紧凑的方式来表达相同的查询,理想情况下不必求助于 JOIN

4

4 回答 4

1

尝试这个..

SELECT EventID, EventType, Timestamp, Description
FROM EventsTable
WHERE EventType = 'B' AND 
      Timestamp = (SELECT max(Timestamp) FROM EventsTable WHERE EventType = 'B');
于 2013-03-02T20:28:15.010 回答
0
SELECT EventID, EventType, Timestamp, Description
FROM EventsTable T
WHERE T.EventType = 'B'
ORDER BY Timestamp
LIMIT 1

应该可以解决问题(对于支持 LIMIT 的 DBMS)。

于 2013-03-02T20:10:43.547 回答
0

没有意识到您只需要返回一行。使用公用表表达式来实现所需的结果。简单而干净。

;WITH CTE
AS
(
    SELECT EventID, 
           EventType, 
           Timestamp,
           Description
    FROM EventsTable 
    WHERE EventType = 'B'
)

SELECT TOP 1 * FROM CTE 
ORDER BY TIMESTAMP DESC
于 2013-03-02T20:15:29.827 回答
0

如果你不想使用 order by 使用这个:

SELECT * FROM EventsTable WHERE EventType = 'B' AND
Timestamp = (SELECT Max(Timestamp) FROM EventsTable WHERE EventType = 'B');

如果订购是可以的:

mysql:

SELECT * FROM EventsTable WHERE EventType = 'B' ORDER BY Timestamp DESC LIMIT 1;

Sql 服务器:

SELECT TOP 1 * FROM EventsTable WHERE EventType = 'B' ORDER BY Timestamp DESC

请看小提琴

于 2013-03-02T20:48:34.080 回答