使用WHERE子句选择MAX date

时间:2014-02-01 15:36:57

标签: mysql sql where maxdate

我有一个名为technical的表,我可以在哪里为查询函数放置WHERE子句吗?

我想插入WHERE t1.blklot LIKE '01/01' - 此行只会显示blklot = 01/01

SELECT * 
FROM technical t1
JOIN (
    SELECT blklot, MAX(date_update) AS MAXDATE
    FROM technical
    GROUP BY blklot
) t2 ON t1.blklot = t2.blklot
AND t1.date_update = t2.MAXDATE
ORDER BY t1.blklot

2 个答案:

答案 0 :(得分:1)

您实际上可以将其放在子查询或外部查询中。在子查询中,您需要更改条件中的表别名。您的条件是用于聚合的密钥,因此它可以在任何一个地方工作。

或者,你可以把它放在on子句中:

ON t1.blklot = t2.blklot and
   t1.date_update = t2.MAXDATE and
   t1.blklot LIKE '01/01'

编辑:

实际上,把它放在子查询中。这是最有效的方式:

SELECT * 
FROM technical t1 JOIN
     (SELECT blklot, MAX(date_update) AS MAXDATE
      FROM technical
      WHERE blklot LIKE '01/01'
     ) t2
     ON t1.blklot = t2.blklot AND
        t1.date_update = t2.MAXDATE
ORDER BY t1.blklot;

因为您只选择一个值,所以不需要group by

答案 1 :(得分:0)

试试这个

SELECT * 
FROM technical t1
  JOIN (
      SELECT blklot, MAX(date_update) AS MAXDATE
      FROM technical
      GROUP BY blklot
      )t2 ON t1.blklot = t2.blklot
      AND t1.date_update = t2.MAXDATE
WHERE t1.blklot LIKE '01/01
ORDER BY t1.blklot

或在ON CLAUSE中创建一个条件

SELECT * 
FROM technical t1
  JOIN (
      SELECT blklot, MAX(date_update) AS MAXDATE
      FROM technical
      GROUP BY blklot
      )t2 ON t1.blklot = t2.blklot
      AND t1.date_update = t2.MAXDATE
      AND t1.blklot LIKE '01/01
ORDER BY t1.blklot