Mysql 在一个查询中从另一个id获取结果的查询

Mysql 在一个查询中从另一个id获取结果的查询,mysql,sql,subquery,case,where-clause,Mysql,Sql,Subquery,Case,Where Clause,我有下面的简单表格 product_id vendor_id product_gtin product_parent_id 646 1 123456789 0 4502 2 202020255 646 因此,我希望从product_父级获得id为4502的产品gtin 结果示例: product_id vendor_id product_gtin pro

我有下面的简单表格

product_id    vendor_id    product_gtin    product_parent_id
646           1            123456789       0
4502          2            202020255       646
因此,我希望从product_父级获得id为4502的产品gtin

结果示例:

product_id    vendor_id    product_gtin    product_parent_id
646           1            123456789       0
4502          2            123456789       646

我的问题是,当我运行查询时,它不知道我引用的是哪个id。因此,对于id为4502的product_gtin,我得到了NULL


如果您对如何解决此问题有任何建议,我们将不胜感激。

您可以使用表别名:

select product_id, vendor_id, 
    case when vendor_id <> 1 
        then (select product_gtin from `products` p1 where p1.product_id = p.product_parent_id) 
        else product_gtin 
    end as gtin, 
    product_parent_id 
from `products` p
where product_id in (646, 4502)
您应该使用自左联接,而不是具有适当别名的子查询来引用列,因为我们两次使用同一个表

select p.product_id, 
       p.vendor_id, 
       case when p.vendor_id != 1 then p1.product_gtin else p.product_gtin end as gtin, 
       p.product_parent_id 
 from `products` p lefr join `products` p1 on p1.product_id = p.product_parent_id
 where p.product_id in (646, 4502)
select p.product_id, 
       p.vendor_id, 
       case when p.vendor_id != 1 then p1.product_gtin else p.product_gtin end as gtin, 
       p.product_parent_id 
 from `products` p lefr join `products` p1 on p1.product_id = p.product_parent_id
 where p.product_id in (646, 4502)