这里的问题是bills
与partners
有关,而不是coupons
。你的SQL,例如,是这样的:
drop table if exists coupons;
create table coupons (id int not null, pid int not null, expires date, primary key(id));
drop table if exists bills;
create table bills (id int not null, pid int not null, `date` date, primary key(id));
drop table if exists partners;
create table partners (id int, name varchar(20), primary key(id));
我们填充一些数据:
insert into partners values (1,'One');
insert into coupons values (1,1,'2011-12-12'), (2,1,'2011-11-11');
insert into bills values (1,1,'2011-12-12'), (2,1,'2011-11-11');
此时
select * from coupons c
left join partners p on c.pid = p.id
left join bills b on b.pid = c.pid
返回4行,这是有道理的:(合作伙伴1 ,coupon1,bill1),(p1,c1,b2),(p1,c2,b1),(p1,c2,b2)。如果再加上:
where
(
current_date() = date_add(c.expires, interval 1 month)
or
current_date() = date_add(b.`date`, interval 1 month)
)
我们得到3行:(P1,C1,B1),(P1,C1,B2),(P1,C2,B1)。为什么?因为coupon2或bill2在测试中都没有成功,而其他组合中至少有一个是成功的。
我怀疑你真正寻找的是更接近:
select *
from coupons c
where
c.id in
(select distinct c2.id from coupons c2
left join partners p2 on c2.pid=p2.id
left join bills b2 on b2.pid=c2.pid
where
current_date()=date_add(c2.expires, interval 1 month)
or
current_date()=date_add(b2.`date`, interval 1 month)
)
在这里我使用子查询来获得不同的优惠券ID列表优惠券符合您的要求,那么就检索这些优惠券。
但是,玩它,我不确定您的要求是否有意义:您正在检索的优惠券或者有一个月前的有效日期,或者是与一个月结算的合作伙伴关联的优惠券前?在这种方法中,您只能获得优惠券清单,然后需要检索最新的帐单或合作伙伴详细信息,假设总是有关联的合作伙伴?在那儿?
希望有帮助,克雷格
你如何确定“最新”的是什么?桌子上有没有可以提供这些信息的字段? – malonso 2012-01-12 12:24:16
是的。 b.'''(法案的日期)应该是最新的。你懂我的意思吗? – Vay 2012-01-12 14:43:04