[英]Select records that dont exist in a table but also include those that exist with where clause exclusion
我有两层。 一层适用于获得至少 1 点积分的客户,另一层适用于获得至少 1000 点积分的客户。
我想获得积分 >= 950 和 < 1000 的客户的记录。我计划将他们移到第二层作为奖励。 我最近导入了客户,即使他们至少有 1 分,也不会自动添加到第一层。
当我进行查询时,它不包括我导入的那些,因为它们不存在于customer_vip_tiers表中。
tier 1 id = 1733
tier 2 id = 1734
select
c.id,
c.email,
sum(p.reward_points) as total_points,
vt.name,
cvt.tier_id
from vip_tiers_settings vts
left join customers c on c.merchant_id = vts.merchant_id
left join customers_vip_tiers cvt on c.id = cvt.customer_id
left join vip_tiers vt on vt.id=cvt.tier_id
left join perks p on p.customer_id = c.id
and p.created_at >= coalesce(vts.custom_start_date,0)
and p.completed = 1
and p.reversed = 0
and p.expired = 0
where
c.merchant_id = 50506
and cvt.tier_id != 1734
group by c.id having sum(p.reward_points) >= '950' and sum(p.reward_points) < '1000'
;
我的理解是,由于我的 where 中的cvt.tier_id != 1734子句,他们没有获得不在层中的记录,因为他们在 customers_vip_tiers 表中没有记录。 我如何才能获得该表中没有记录的那些?
我得到了答案。
我摆脱了cvt.tier_id != 1734 。
select
c.id,
c.email,
sum(p.reward_points) as total_points,
vt.name,
cvt.tier_id
from vip_tiers_settings vts
left join customers c on c.merchant_id = vts.merchant_id
left join customers_vip_tiers cvt on c.id = cvt.customer_id
left join vip_tiers vt on vt.id=cvt.tier_id
left join perks p on p.customer_id = c.id
and p.created_at >= coalesce(vts.custom_start_date,0)
and p.completed = 1
and p.reversed = 0
and p.expired = 0
where
c.merchant_id = 50506
and c.id not in(select customer_id from customers_vip_tiers cvv where cvv.merchant_id=50506 and cvv.tier_id=1734)
group by c.id having sum(p.reward_points) >= '950' and sum(p.reward_points) < '1000';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.