Mysql 我怎样才能只得到被替换了整整3次的产品?
我在解决如何编写一个查询时遇到了问题,该查询只会返回一个产品的行,而该产品恰好被替换了3次 我添加了V1、V2、V3文本位来帮助解释这个问题,所以我不能只做“包含”V3,因为它不存在 以下是我的数据表:Mysql 我怎样才能只得到被替换了整整3次的产品?,mysql,sql,database,Mysql,Sql,Database,我在解决如何编写一个查询时遇到了问题,该查询只会返回一个产品的行,而该产品恰好被替换了3次 我添加了V1、V2、V3文本位来帮助解释这个问题,所以我不能只做“包含”V3,因为它不存在 以下是我的数据表: +-----------+--------------+--------------+ | ProductId | SupersededBy | Name | +-----------+--------------+--------------+ | 123456 | 78
+-----------+--------------+--------------+
| ProductId | SupersededBy | Name |
+-----------+--------------+--------------+
| 123456 | 789012 | Car Wheel V1 |
| 789012 | 345678 | Car Wheel V2 |
| 345678 | null | Car Wheel V3 |
| 901234 | 112233 | Brake Pad V1 |
| 567890 | 778899 | Mirror V1 |
| 112233 | null | Brake Pad V2 |
| 445566 | null | Mirror V3 |
| 778899 | 445566 | Mirror V2 |
| 113366 | 224477 | Motor V1 |
| 224477 | 335588 | Motor V2 |
| 335588 | 990011 | Motor V3 |
| 990011 | null | Motor V4 |
+-----------+--------------+--------------+
预期产出:
+-----------+--------------+--------------+
| ProductId | SupersededBy | Name |
+-----------+--------------+--------------+
| 345678 | null | Car Wheel V3 |
| 445566 | null | Mirror V3 |
+-----------+--------------+--------------+
您可以使用
join
s精确跟踪链两次(以获得三种产品):
不存在
是为了确保您从第一个产品开始。理想情况下,您还可以为“组”添加一个版本,以使查询更简单。。另外,作为MySQL 8,您使用的是哪个MySQL版本使这变得更容易。。
select t.ProductId, t2.ProductId, t3.ProductId
from t t1.join
t t2
on t2.SupersededBy = t1.ProductId join
t t3
on t3.SupersededBy = t2.ProductId
where t3.SupersededBy is null and
not exists (select 1
from t t2
where t2.SupersededBy = t1.ProductId
);