gpt4 book ai didi

mysql - 从子内连接选择引用父字段

转载 作者:行者123 更新时间:2023-11-29 07:44:42 24 4
gpt4 key购买 nike

我有一个从表中选择记录并左连接其他两个表的查询。

这是查询

SELECT mainTest.lab_number_auto, mainTest.lab_number,
SUM(CASE WHEN test.lab_number = mainTest.lab_number
THEN test.test_unit_cost ELSE 0 END) cost,
payment.totalPaid

FROM patient_main_test mainTest

LEFT JOIN patient_test test
ON test.lab_number = mainTest.lab_number

LEFT JOIN (
SELECT SUM(CASE WHEN testpayment.lab_number = mainTest.lab_number THEN testpayment.amount_paid ELSE 0 END) totalPaid
FROM patient_test_payment testpayment
GROUP BY testpayment.lab_number
) AS payment
ON payment.lab_number = mainTest.lab_number

WHERE mainTest.lab_number != ''
GROUP BY mainTest.lab_number

运行此查询时,我收到此错误

MySQL said:
#1054 - Unknown column 'mainTest.lab_number' in 'field list'

谢谢。

这是我创建的 fiddle 。 http://sqlfiddle.com/#!2/291c4/8

最佳答案

试试这个,如果我是对的,问题是您试图将左连接中的派生表视为相关子查询。感谢 sql fiddle...使帮助您变得更加容易。

SELECT mainTest.lab_number_auto, mainTest.lab_number,
SUM(CASE WHEN test.lab_number = mainTest.lab_number
THEN test.test_unit_cost ELSE 0 END) cost,
(
SELECT SUM(CASE WHEN testpayment.lab_number = mainTest.lab_number THEN testpayment.amount_paid ELSE 0 END) totalPaid
FROM patient_test_payment testpayment
Where lab_number = mainTest.lab_number
GROUP BY testpayment.lab_number
) AS totalPaid

FROM patient_main_test mainTest

LEFT JOIN patient_test test
ON test.lab_number = mainTest.lab_number

WHERE mainTest.lab_number != ''
GROUP BY mainTest.lab_number

关于mysql - 从子内连接选择引用父字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148065/

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