mySQL Query获取不匹配的记录

时间:2013-04-23 20:59:28

标签: mysql

我有一个SQL查询,我希望添加另一个条件,但我似乎无法让它工作。查询很简单:

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

但是我希望从给定日期中没有记录的monthly_returns中获取记录。我知道会是这样的

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

paidreturns.paid = 0是未支付账单的地方,但如果在付款回收中没有该日期的记录,那么该账单也没有支付。

架构

payreturns表

-id

-company_id

-paid

- 月

-total

monthly_returns表

-id

-company_id

-wage_totals

- 月

2 个答案:

答案 0 :(得分: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,您可以在查询中包含这些不匹配的条目。

答案 1 :(得分: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