0

我有一个 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

但是,我还希望从在给定日期的支付回报中根本没有记录的每月回报中获取记录。我知道会是这样的

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

paidreturns.paid =0 是未支付账单的地方,但同样,如果在paidreturns 中没有该日期的记录,则也不会支付账单。

架构

支付回报表

-ID

-company_id

-有薪酬的

-月

-全部的

每月回报表

-ID

-company_id

-wage_totals

-月

4

2 回答 2

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
        );

使用 a LEFT JOIN,您可以找到来自 的所有记录monthly_returns,无论它们是否与来自 的条目匹配paidreturns

然后,通过添加paidreturns.company_id IS NULLWHERE子句中,您可以在查询中包含那些不匹配的条目。

于 2013-04-23T21:03:26.823 回答
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
于 2013-04-23T21:02:31.243 回答