gpt4 book ai didi

Mysql嵌套查询访问父字段值

转载 作者:行者123 更新时间:2023-11-30 22:25:17 25 4
gpt4 key购买 nike

我需要访问嵌套到嵌套查询中的父字段值。这是我的查询

    SELECT

(
sum(co.product_baseprice) + (
select COALESCE(sum(testsum), 0)
from (SELECT
COALESCE (SUM(rm_baseprice), 0) * COALESCE (rm_quantity, 0) as testsum
FROM
rm_orders
WHERE
order_id = o.id
GROUP BY
id
order by
id) as temp1)
) AS p_baseprice,
(
sum(co.product_vat)
) AS p_vat,
o.surcharge_value_id
FROM
orders AS o
INNER JOIN customer_orders AS co ON o.id = co.order_id
WHERE
1 = 1
-- o.id = 62720
GROUP BY
o.id
ORDER BY
ValueAfterVAT DESC
LIMIT 25;

在 sub to sub 查询中,您发现字段 o.id 是订单表的字段。当我尝试执行此查询时,我会看到类似

的错误
"Error Code: 1054. Unknown column 'o.id' in 'where clause'  0.000 sec"

如何在嵌套到嵌套查询中访问 o.id。

最佳答案

实际上你不需要在内部查询中与父字段连接,将它放在外部查询中。

SELECT 
sum(co.product_baseprice) + (p_baseprice.testsum),
o.id, co.product_vat AS p_vat,
o.surcharge_value_id
FROM
orders AS o
INNER JOIN customer_orders AS co ON o.id = co.order_id
-- here query from SELECT was placed there. Note! LEFT OUTER
-- used since you used COALESCE
LEFT OUTER JOIN (
SELECT order_id,
COALESCE (SUM(rm_baseprice), 0) * COALESCE (rm_quantity, 0) as testsum
FROM
rm_orders
GROUP BY
order_id
) as p_baseprice ON p_baseprice.order_id = o.id
WHERE ...

关于Mysql嵌套查询访问父字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429567/

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