MySQL如何选择最小值和最大值之间的日期记录

时间:2018-03-17 11:51:26

标签: mysql sql

假设我有四个日期,例如:

  • 2018年1月1日
  • 2018年2月5日
  • 2018年4月8日
  • 2018年9月9日

我想选择'最小值和最大值之间的日期。无论是2/5/2018记录还是4/8/2018记录。

我想我已关闭,但此查询会返回所有行:

SELECT * FROM RUBERIC R  
WHERE R.SCHOOLID = 75 
AND R.TEACHERID = 610 
AND R.OBSERVED = 'Observed Classroom' 
AND R.DATE BETWEEN 
(SELECT MIN(DATE) FROM RUBERIC WHERE R.SCHOOLID = 75 
AND R.TEACHERID = 610 AND R.OBSERVED = 'Observed Classroom' )
AND
(SELECT MAX(DATE) FROM RUBERIC WHERE R.SCHOOLID = 75 
AND R.TEACHERID = 610 AND R.OBSERVED = 'Observed Classroom' )

3 个答案:

答案 0 :(得分:0)

BETWEEN包括终点。据推测,你想要排除它们:

SELECT R.*
FROM RUBERIC R  
WHERE R.SCHOOLID = 75 AND
      R.OBSERVED = 'Observed Classroom' AND
      R.DATE > (SELECT MIN(R2.DATE) FROM RUBERIC R2 WHERE R2.SCHOOLID = 75 
AND R2.TEACHERID = 610 AND R2.OBSERVED = 'Observed Classroom'
               ) AND
      R.DATE < (SELECT MAX(R2.DATE) FROM RUBERIC R2 WHERE R2.SCHOOLID = 75 
AND R2.TEACHERID = 610 AND R2.OBSERVED = 'Observed Classroom'
               );

此外,您的查询 - 无意中 - 是一个相关的子查询。表别名R引用主查询中的行,而不是子查询。您应该始终定义表别名并始终使用它们,但要正确使用它们。 (注意此版本子查询中的所有R2。)

一般来说,我强烈反对任何人使用BETWEEN日期或日期/时间。在您的情况下这不是问题,但时间组件可能会导致意外结果。

答案 1 :(得分:0)

这是因为BETWEEN具有包容性。请参阅此answer

答案 2 :(得分:0)

您的BETWEEN条件不会对结果集进行任何更改,因为MIN和MAX将包含在内。您需要将BETWEEN条件拆分为<>条件。但是为了不复制SCHOOLID,TEACHERID和OBSERVED上的条件,我首先在子查询中选择最小和最大日期,然后将表连接到它。

SELECT R.*
FROM (
    SELECT SCHOOLID, TEACHERID, OBSERVED, MIN(DATE) AS MIN_DATE, MAX(DATE) AS MAX_DATE
    FROM RUBERIC
    WHERE SCHOOLID  = 75 
      AND TEACHERID = 610 
      AND OBSERVED  = 'Observed Classroom'
) X
JOIN RUBERIC R
  ON  R.SCHOOLID  = X.SCHOOLID
  AND R.TEACHERID = X.TEACHERID
  AND R.OBSERVED  = X.OBSERVED
  AND R.DATE      > X.MIN_DATE
  AND R.DATE      < X.MAX_DATE

如果您需要选择&#34;任何&#34;其中一行,只需在查询末尾添加LIMIT 1