查询不返回所有预期的行

时间:2012-02-24 12:51:10

标签: mysql sql

SELECT p.INVOICE_PAYMENT_ID,i.INVOICE_ID,i.INVOICE_NUMBER,i.CLINIC_ID,
    i.INVOICE_DATE,i.PAYMENT_RECEIVED_DATE, i.AMOUNT,
    i.CURRENT_CHARGE,i.AMOUNT_RECEIVED,i.MONTH,i.YEAR,i.COMPANY_ID,
    i.COMPANY_NAME,c.NAME,p.NOTE,i.NOTES
FROM test1 i 
LEFT JOIN test2 c ON (i.CLINIC_ID=c.CLINIC_ID)
LEFT JOIN test3 p ON p.INVOICE_ID=i.INVOICE_ID  
WHERE i.MONTH=11 AND i.YEAR=2011                     
    AND  p.INVOICE_PAYMENT_ID IN (
        SELECT MAX(INVOICE_PAYMENT_ID) 
        FROM test3 WHERE INVOICE_ID=i.INVOICE_ID 
    )

如果内部查询没有值,则它不会返回test3中的所有相应行。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

将内部查询从where子句移动到join条件:

SELECT p.INVOICE_PAYMENT_ID,i.INVOICE_ID,i.INVOICE_NUMBER,i.CLINIC_ID,
    i.INVOICE_DATE,i.PAYMENT_RECEIVED_DATE, i.AMOUNT,
    i.CURRENT_CHARGE,i.AMOUNT_RECEIVED,i.MONTH,i.YEAR,i.COMPANY_ID,
    i.COMPANY_NAME,c.NAME,p.NOTE,i.NOTES
FROM test1 i 
LEFT JOIN test2 c ON (i.CLINIC_ID=c.CLINIC_ID)
LEFT JOIN test3 p ON p.INVOICE_ID=i.INVOICE_ID and p.INVOICE_PAYMENT_ID = (
        SELECT MAX(INVOICE_PAYMENT_ID) 
        FROM test3 WHERE INVOICE_ID=i.INVOICE_ID)
WHERE i.MONTH=11 AND i.YEAR=2011

答案 1 :(得分:0)

您可以更改实际的where子句:

... AND 
    p.INVOICE_PAYMENT_ID IN 
    (SELECT MAX(INVOICE_PAYMENT_ID) 
     FROM test3 WHERE INVOICE_ID=i.INVOICE_ID )

由:

... AND
(
    not exists 
    (SELECT MAX(INVOICE_PAYMENT_ID) 
    FROM test3 WHERE INVOICE_ID=i.INVOICE_ID ) 
 OR
    p.INVOICE_PAYMENT_ID IN 
    (SELECT MAX(INVOICE_PAYMENT_ID) 
     FROM test3 WHERE INVOICE_ID=i.INVOICE_ID )
)

如果没有此montn和条件的数据,这将返回test3。