0

嗨,我们有一个看起来像这样的表(称为表 A)。如果父数据和子数据,它包含两行。如果存在,我需要获取如下包含 item_id 和 parent_item_id 的行(否则为 item_id)。现在我需要加入

item_id (if parent) + parent_item_id as new_iditem_id (if no parent) + item_id as new_id

我已经使用了IFNULL这样的函数IFNULL(parent_item_id, item_id) as new_id,然后我使用new_id再次加入同一张表 A 上的 item_id 以获得一些最终值

长话短说,我的查询是

select item_id, IFNULL(parent_item_id, item_id) AS new_id 
from table A as A1
INNER JOIN table A as A2 ON A1.new_id = A2.item_id 
where A1.type = simple

问题是我似乎不允许使用我新创建的列再次加入同一个表new_id

问题:如何改写此查询以便允许我的加入?还是有更聪明的方法可以完全完成这项工作?

数据示例

|--item_id --|--parent_item_id--|---type---|--price--|
   123          124               simple     0.00
   124          null              config     9.00
   125          null              simple     8.00

我需要在变量列上加入这个表 A

错误是

查询中的错误 (1054):“on 子句”中的未知列“new_id”

4

2 回答 2

1

将计算直接放入INNER JOIN中,如下所示:

select item_id, IFNULL(parent_item_id, item_id) AS new_id 
from table A as A1
INNER JOIN table A as A2 ON IFNULL(A1.parent_item_id, A1.item_id) = A2.item_id 
where A1.type = simple
于 2017-01-10T05:03:46.883 回答
0
select * from A as A2 
JOIN
(
select item_id, type, IFNULL(parent_item_id, item_id)  AS new_id from  A
)A1
ON (A1.new_id = A2.item_id)
where A1.type = 'simple'
于 2017-01-08T22:40:39.000 回答