为什么这个查询的行为不像我期望的那样?

时间:2012-08-10 08:26:42

标签: mysql

有问题的查询是

SELECT MAX(Date) as max, MIN(Date) as min FROM 
table 
WHERE Id = 'id' 
ORDER BY Date DESC 
LIMIT 100

我想要它做的是返回最近100条记录的最长和最短日期。它的作用是显示所有记录的最小值和最大值。

3 个答案:

答案 0 :(得分:2)

您必须首先选择您感兴趣的记录,然后从这些记录中选择max()min()

SELECT max(Date) AS max,
       min(Date) AS min
  FROM ( SELECT *
           FROM t
          WHERE Id = 'id'
       ORDER BY Date DESC
          LIMIT 100) x;

答案 1 :(得分:2)

不要忘记用反引号转义列。

SELECT max(`date`) AS maxDate,
       min(`date`) AS minDate
FROM  ( 
         SELECT `date`
         FROM   myTable
         WHERE Id = 'id'
         ORDER BY `date` DESC
         LIMIT 100
      )

答案 2 :(得分:1)

select min(Date) as min, max(Date) as max from
(
     SELECT Date FROM your_table 
     WHERE Id = 'id' 
     ORDER BY Date DESC  
     LIMIT 100
) x