【问题标题】:Select records that dont exist in a table but also include those that exist with where clause exclusion选择表中不存在的记录,但也包括使用 where 子句排除存在的记录
【发布时间】:2020-11-19 16:35:47
【问题描述】:

我有两层。一层适用于获得至少 1 分的客户,另一层适用于获得至少 1000 分的客户。

我想获取积分 >= 950 且

当我进行查询时,它不包括我导入的那些,因为它们不存在于 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 表中没有记录。我如何也可以获取该表中没有记录的那些?

【问题讨论】:

  • 你的 vip_tiers_settings 表有这些客户吗?
  • 没有。这只是层的设置。 @user3315556
  • 那么,您已经在客户表中导入了客户?如果有,他们有 Mercer_id 吗?
  • @user3315556 是的,他们确实有商家 ID
  • 我认为一种解决方法是您可以将客户 c 上的左连接更改为右连接。

标签: mysql sql mariadb


【解决方案1】:

我得到了答案。

我摆脱了 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';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-30
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多