引用外部列正在处理的subquerys是否有限制?
我尝试了这个查询:
SELECT
`userouter`.`id` AS `user_id`
FROM
`users` AS `userouter`
WHERE
123456 = (
SELECT
SUM(`tmp`.`sum`) AS `sum_total`
FROM
(
SELECT
SUM(`invoiceposition`.`number` * `invoiceposition`.`amount`) AS `sum`
FROM
`invoices` AS `invoice` INNER JOIN
`invoicepositions` AS `invoiceposition` ON
`invoice`.`id` = `invoiceposition`.`invoice`
WHERE
`invoice`.`user` = `userouter`.`id`
GROUP BY
`invoice`.`id`
) AS `tmp`
)
GROUP BY
`userouter`.`id`
我得到Error Code: 1054. Unknown column 'userouter.id' in 'where clause'
如何在子查询中引用userouter.id
?
答案 0 :(得分:1)
由于看起来似乎无法解决问题(双嵌套子查询引用外部查询),我现在通过创建一个用户id为参数的mysql函数来解决问题。
希望这会有助于其他搜索者
答案 1 :(得分:0)
删除双重嵌套。
SELECT
`userouter`.`id` AS `user_id`
FROM
`users` AS `userouter`
LEFT JOIN (
SELECT
`invoice`.`user` as `user_id`, SUM(`invoiceposition`.`number` * `invoiceposition`.`amount`) AS `sum`
FROM
`invoices` AS `invoice` INNER JOIN
`invoicepositions` AS `invoiceposition` ON
`invoice`.`id` = `invoiceposition`.`invoice`
WHERE
`invoice`.`user` = `userouter`.`id`
GROUP BY
`invoice`.`id`
) AS `tmp`
ON `tmp`.`user_id` = `userouter`.`id`
WHERE
123456 = `userouter`.`id`
GROUP BY
`userouter`.`id`