我有3张桌子优惠券,cp,mcr。我想获得表cp和mcr中优惠券的所有记录,其中cp(状态='活跃')和mcr(状态='兑换')存在某些条件。我想要所有活跃或兑换的优惠券。该信息以cp和mcr传播。
我想要activity1 union activity2的所有记录。我尝试使用activity1和activity2进行正确的连接,但没有得到它。我如何得到我需要的结果。以下是我的查询
insert into cp (coupon, phone, status) values (8, 'xxxxxxxxxxxx', 'deleted');
insert into mcr (coupon, customer, coupon_code, phone, status) values (8, 'cf6a842e-6fc2-4587-88ca-46ea6424636c', 'ABCD', 'xxxxxxxxxxxx', 'redeemed')
select coupon.id, mcr.id as mcr, cp.id as cp
from coupon
left JOIN mcr ON coupon.id=mcr.coupon
LEFT JOIN cp ON cp.coupon=coupon.id
where mcr.status='redeemed'
and mcr.phone='xxxxxxxxxxxx'
and cp.status='active';
SQL> describe cp;
Name Null? Type
----------------------------------------- -------- ----------------------------
COUPON NUMBER(38)
PHONE CHAR(12)
STATUS NOT NULL VARCHAR2(50)
CREATE_TS NOT NULL TIMESTAMP(6)
ID NOT NULL NUMBER(38)
SQL> describe mcr;
Name Null? Type
----------------------------------------- -------- ----------------------------
COUPON NOT NULL NUMBER(38)
CUSTOMER NOT NULL CHAR(36)
PHONE CHAR(12)
COUPON_CODE NOT NULL VARCHAR2(64)
STATUS VARCHAR2(200)
CREATE_TS NOT NULL TIMESTAMP(6) WITH TIME ZONE
VERIFY_TS TIMESTAMP(6) WITH TIME ZONE
REDEEM_TS TIMESTAMP(6) WITH TIME ZONE
ID NOT NULL NUMBER(38)
我在coupon_phone中有有效记录,但在merchant_coupon_redeem中没有。我无法通过上述查询获得任何结果。
答案 0 :(得分:0)
我认为以下查询会为您提供所需的输出。但请保留表中的一些常用数据,以便在满足这些条件的情况下至少记录一条记录。
select coupon.id as cid,
merchant_coupon_redeem.id as mcr,
coupon_phone.id as cp
from coupon
left JOIN merchant_coupon_redeem ON cid=merchant_coupon_redeem.coupon
left JOIN coupon_phone ON coupon_phone.coupon=cid
where merchant_coupon_redeem.status='redeemed'
and merchant_coupon_redeem.phone='xxxxxxxxxx'
and coupon_phone.status='active';