简体   繁体   English

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

[英]How to select newest records from table with many-to-many relationship

I have two tables.Table Products in which there are two product types ProductType_1 and ProductType_2 , and second table ProductType_2_Items in which I keep the information that ProductType_1 is contained in ProductType_2 . 我有两个表。表Products中有两个产品类型ProductType_1ProductType_2 ,第二个表ProductType_2_Items在其中保存了ProductType_1包含在ProductType_2 I need to get the latest (published_at) ProductType_1 for each ProductType_2 . 我需要获得最新的(published_at) ProductType_1每个ProductType_2

Products table: 产品表:

|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 table: ProductType_2_Items表:

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

Expected result: 预期结果:

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

Thanks for all replies. 感谢您的所有回复。

You can try below - 您可以在下面尝试-

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 

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

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