简体   繁体   English

MySQL为派生的最大功能列添加条件

[英]mysql add condition for derived max function column

I have the following sql which is not working on the where condition. 我有以下sql在where条件下不起作用。

SELECT t.PROJID,sum(t.UNITS) AS totalunits, sum(t.COST) AS totalcost, project, max(t.DATE) as lastupdated, PROJCODE 
FROM `projectcosts` `t` 
left join projects on projects.PROJID = t.PROJID 
where lastupdated LIKE '%2014-06-11%' 
GROUP BY t.PROJID

You should not use like on dates. 您不应该在日期上使用like The right solution is to simply truncate the date and do the comparison. 正确的解决方案是简单地截断日期并进行比较。 However, you need to use the field in the data: 但是,您需要使用数据中的字段:

SELECT t.PROJID, sum(t.UNITS) AS totalunits,
       sum(t.COST) AS totalcost, project, max(t.DATE) as lastupdated, PROJCODE 
FROM `projectcosts` `t` left join
     projects on projects.PROJID = t.PROJID 
where date(t.date) = date('2014-06-11')
GROUP BY t.PROJID;

Or, if you have an index on lastupdated , using a range allows the use of the index: 或者,如果您在lastupdated上具有索引,则使用范围可以使用索引:

SELECT t.PROJID, sum(t.UNITS) AS totalunits,
       sum(t.COST) AS totalcost, project, max(t.DATE) as lastupdated, PROJCODE 
FROM `projectcosts` `t` left join
     projects on projects.PROJID = t.PROJID 
where t.date >= date('2014-06-11') and t.date < date('2014-06-12')
GROUP BY t.PROJID;

You might really be wanting to use having , which is suggested by the use of the column alias instead of the base column. 您可能真的想使用having ,这是通过使用列别名而不是基础列来建议的。 In that case: 在这种情况下:

SELECT t.PROJID, sum(t.UNITS) AS totalunits,
       sum(t.COST) AS totalcost, project, max(t.DATE) as lastupdated, PROJCODE 
FROM `projectcosts` `t` left join
     projects on projects.PROJID = t.PROJID 
GROUP BY t.PROJID
HAVING date(lastupdated) = date('2014-06-11');

Like can never be used with date field. Like不能与日期字段一起使用。 If you are changing the type to vachar it is possible 如果您将类型更改为vachar,则可以

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM