gpt4 book ai didi

mysql - Sql 查询,table/w 双行,join on IFNULL 函数 - 表 join on tiself 与变量列

转载 作者:行者123 更新时间:2023-11-29 11:05:05 26 4
gpt4 key购买 nike

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

item_id(如果是父项)+parent_item_id 作为 new_iditem_id(如果没有父项)+ item_id 作为 new_id

我使用了 IFNULL 函数,例如 IFNULL(parent_item_id, item_id) as new_id,然后我使用 new_id 加入再次针对 item_id 获取相同的表 A 以获得一些最终值

长话短说,我的查询是

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 加入到变量列上

错误是

Error in query (1054): Unknown column 'new_id' in 'on clause'

最佳答案

将计算直接放入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

关于mysql - Sql 查询,table/w 双行,join on IFNULL 函数 - 表 join on tiself 与变量列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com