Sql:仅选择连接表的值等于1的值

时间:2015-02-27 10:37:42

标签: mysql sql

我在mysql中有这些表

ADS
ID
1
2
PAYMENTS
id  ads_id
1   1
2   1
3   1
4   2
5   2
INSTALLMENTS
id Payment_id paid
1  1          1         
2  1          0
3  2          1
4  2          1
5  3          1
6  4          0
7  4          1
8  5          0

我想了解只有所有分期付款的广告.paid = 1。

例如,ads.id = 1的返回值为2(只有payment.id 2 AND 3包含所有installments.paid = 1),0表示ads.id = 0

我试过

SELECT ads.id AS id, 
    (
    select count(*)
    from payments
    where 
        (SELECT count(*)
        FROM installments
        where (installments.payment_id = payments.id AND (installments.paid = 0))) <1 
            AND payments.ad_id = ads.id
    )
FROM ads 
LEFT JOIN payments ON ads.id = payments.ad_id 
LEFT JOIN installments ON installments.payment_id = payments.id
GROUP BY ads.id

但不起作用

1 个答案:

答案 0 :(得分:0)

解决此问题的一种方法是使用group byhaving。要获取广告ID,您实际上并不需要广告表,因为分期付款具有以下信息:

select i.ads_id
from installments i join
     payments p
     on i.payment_id = p.id
group by i.ads_id
having min(i.paid) = 1 and min(i.paid) = max(i.paid);

请注意,这是检查最小值和最大值 - 以防万一其他值进入。如果值可能是NULL,您还需要and count(*) = count(i.paid)

另一种解决方法是使用not existsnot in

select a.*
from ads a
where not exists (select 1
                  from installments i join
                       payments p
                       on i.payment_id = p.id
                  where p.ads_id = a.id and i.paid <> 0
                 );