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

时间:2015-01-26 10:09:34

标签: mysql sql

我有这个查询,从表中选择记录,LEFT JOINS其他两个表。

这是查询

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' 

感谢。

这是我创造的小提琴。 http://sqlfiddle.com/#!2/291c4/8

1 个答案:

答案 0 :(得分:2)

尝试这个,如果我正确的问题是你试图在左连接中处理你的派生表,就像一个共同相关的子查询。 &安培;对于sql小提琴来说......让你更容易帮助你。

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