简体   繁体   English

在mysql中没有匹配条件的情况下获取最新记录

[英]Get latest records without matching condtion in mysql

I would like to get latest records even though without matching the conditions in MYsql. 即使不符合MYsql中的条件,我也想获取最新记录。

In example, I want to select data on 2013-01-20 by group by product type, but it doesn't match this condition, So it will get the latest date of those product type (2013-01-19 or 2013-01-15). 例如,我想按产品类型分组选择2013-01-20上的数据,但此条件不匹配,因此它将获得这些产品类型的最新日期(2013-01-19或2013-01 -15)。

Coding:

Select date from tblproducttype where 
date=(select max(date) from tblproducttype group by type) where date='2013-01-20'


Table product type

ID  Type  Date
1   2     2013-01-20
2   2     2013-01-20
3   2     2013-01-14
4   3     2013-01-19
5   4     2013-01-16
6   4     2013-01-13

Result should be the following: 结果应为以下内容:

ID  Type  Date
1   2     2013-01-20
2   2     2013-01-20
4   3     2013-01-19
5   4     2013-01-16

For results, i want to combine the data for 2013-01-20 with the latest data for other products. 为了获得结果,我想将2013年1月20日的数据与其他产品的最新数据结合起来。

Finally, we can get only latest date of those product type. 最后,我们只能获得这些产品类型的最新日期。

How to do that in MYSQL? 如何在MYSQL中做到这一点?

Regards. 问候。

I think this is what you want: 我认为这是您想要的:

SELECT p.*
FROM product_type p
JOIN (SELECT Type, MAX(Date) maxdate
      FROM prodct_type
      GROUP BY Type) m
ON p.Type = m.Type and p.Date = m.maxdate

The m subquery finds the latest date for each type. m子查询查找每种类型的最新日期。 The join then finds all rows for each type on that date. 然后,该联接将查找该日期每种类型的所有行。

To filter out a condition, use a HAVING clause in the subquery: 若要过滤条件,请在子查询中使用HAVING子句:

SELECT p.*
FROM product_type p
JOIN (SELECT Type, MAX(Date) maxdate
      FROM prodct_type
      GROUP BY Type
      HAVING maxdate != '2013-01-20') m
ON p.Type = m.Type and p.Date = m.maxdate

or a WHERE clause in the main query: 或主查询中的WHERE子句:

SELECT p.*
FROM product_type p
JOIN (SELECT Type, MAX(Date) maxdate
      FROM prodct_type
      GROUP BY Type) m
ON p.Type = m.Type and p.Date = m.maxdate
WHERE maxDate != '2013-01-20'

You can do this by aggregating the data to get the maximum date and then joining this information back to the original table: 您可以通过汇总数据以获取最大日期,然后将此信息重新加入原始表来做到这一点:

select t.id, t.type, t.date
from t join
     (select type, max(date) as maxdate
      from t
      group by type
     ) tsum
     on t.type = tsum.type and t.date = tsum.maxdate
order by id;

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

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