2013-04-23 86 views
0

我有一個sql查詢,我想添加另一個條件,但我似乎無法得到它的工作。該查詢很簡單:mySQL查詢得到的記錄不匹配

SELECT DISTINCT monthly_returns.company_id 
     FROM monthly_returns, paidreturns 
     WHERE monthly_returns.company_id = paidreturns.company_id 
     AND paidreturns.month = '$cdate' 
     AND paidreturns.paid =0 

但是我想從那些尚未在paidreturns對於給定日期的所有記錄monthly_returns得到記錄也。我知道這將是這樣的

SELECT * 
FROM monthly_returns 
WHERE monthly_returns NOT IN (SELECT * FROM paidreturns WHERE paidreturns.month = '$cdate') 

paidreturns.paid = 0時,由票據尚未支付,但如果同樣存在於paidreturns該日期,然後該法案也沒有支付任何記錄。

架構

paidreturns表

-id

-company_id

-paid

個月的

-total

monthly_returns表

-id

-company_id

-wage_totals

個月的

+0

您可能會考慮使用'LEFT JOIN'將'paidreturns'加入'monthly_returns'。無論「paidreturns」中是否有匹配的行,這將返回所有'monthly_returns'。 http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins – showdev 2013-04-23 21:02:27

回答

1

試試這個:

SELECT 
    DISTINCT monthly_returns.company_id 
FROM 
    monthly_returns 
LEFT JOIN 
    paidreturns 
    ON monthly_returns.company_id = paidreturns.company_id 
     AND monthly_returns.month = paidreturns.month 
WHERE 
    monthly_returns.month = '$cdate' 
    AND 
     (
     paidreturns.paid = 0 
     OR 
     paidreturns.company_id IS NULL 
     ); 

使用LEFT JOIN,您可以找到monthly_returns中的所有記錄,無論它們是否與paidreturns中的條目匹配。

然後,通過將paidreturns.company_id IS NULL添加到WHERE子句中,可以在查詢中包含那些不匹配的條目。

+0

我收到錯誤:SQLSTATE [42S22]:未找到列:1054'where子句'中未知列'paidreturns' – 2013-04-23 21:07:55

+0

我剛剛更新了它,但在架構上仍然有點模糊。你可以從'DESC paidreturns;'和'DESC monthly_returns;'發佈你的輸出嗎? – 2013-04-23 21:09:31

+0

感謝您的幫助,現在的SQL運行,但總是給零記錄我會張貼計劃 – 2013-04-23 21:19:34

0
select company_id 
from 
(
(

SELECT DISTINCT monthly_returns.company_id 
    FROM monthly_returns, paidreturns 
    WHERE monthly_returns.company_id = paidreturns.company_id 
    AND paidreturns.month = '$cdate' 
    AND paidreturns.paid =0 
) 
union 
(


SELECT company_id 
FROM monthly_returns 
WHERE monthly_returns NOT IN (SELECT * FROM paidreturns WHERE paidreturns.month = '$cdate' 
) 
) as x 
+0

你可能想改變工會的第二部分,使內部加入付款返還paidvalue = 0 – Val 2013-04-23 21:03:20

+0

感謝您的重播,我得到你有你的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在第20行'as x'附近使用正確的語法 – 2013-04-23 21:21:00