mysql - 如何从具有多对多关系的表中选择最新记录

标签 mysql greatest-n-per-group

我有两个表。表 Products 其中有两种产品类型 ProductType_1ProductType_2,第二个表 ProductType_2_Items 其中我保留了 ProductType_1 包含在 ProductType_2 中的信息。我需要为每个 ProductType_2 获取最新的(published_at)ProductType_1

产品表:

|id | published_at        | type          |
|---|---------------------|---------------|
| 1 | 2019-04-24 08:23:35 | ProductType_1 |
| 2 | 2019-05-24 08:23:35 | ProductType_1 |
| 3 | 2019-06-24 08:23:35 | ProductType_1 |
| 4 | 2019-04-24 08:23:35 | ProductType_1 |
| 5 | 2019-05-24 08:23:35 | ProductType_1 |
| 6 | 2019-05-24 08:23:35 | ProductType_2 |
| 7 | 2019-05-24 08:23:35 | ProductType_2 |

ProductType_2_Items 表:

| ProductType_2_ID | ProductType_1_ID |
|------------------|------------------|
| 6                | 1                |
| 6                | 2                |
| 6                | 3                |
| 7                | 4                |
| 7                | 5                |

预期结果:

|ProductType_1_ID | published_at        | ProductType_2_ID |
|-----------------|---------------------|------------------|
| 3               | 2019-06-24 08:23:35 | 6                |
| 5               | 2019-05-24 08:23:35 | 7                |

感谢所有回复。

最佳答案

你可以试试下面-

select A.id,p.published_at,a.ProductType_2_ID from
(
   select ProductType_2_ID,max(ProductType_1_ID) as id
   from ProductType_2_Items
   group by ProductType_2_ID
)A inner join Products p on p.id=A.id 

关于mysql - 如何从具有多对多关系的表中选择最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56016263/

相关文章:

mysql - 如何在 MYSQL 中通过另一列选择具有 MAX(列值)、PARTITION 的行?

具有where条件的第二大值的SQL查询

java - 带有 MySql 数据库的 Spring Boot/Web

php - MySQL更新一些数据库字段而不覆盖字段未更改

MySQL - 将日期范围扩展为单个日期

php - 更新包含外键时出错

mysql - 使用街道地址作为主键的最佳实践是什么?

具有线性插值和分组依据的 SQL 查询

php - 在虚拟名册上对用户进行分组

mysql - 生成此报告的最有效方法是什么?