【问题标题】:How to get list of customers that haven't order in last 30 Days in SQL? [duplicate]如何在 SQL 中获取过去 30 天内未订购的客户列表? [复制]
【发布时间】:2020-04-02 10:36:37
【问题描述】:

我有两张桌子

  1. laces_users_profile
  2. laces_order

laces_order 有所有用户的订单列表。 laces_users_profile 拥有所有客户数据。

laces_users_profile 具有唯一键 laces_user_id,即 laces_order 中的外键。

我的表格是这样的

laces_orders

laces_users_profile

我要检索过去 30 天内没有订购的所有客户。

【问题讨论】:

  • 参考stackoverflow.com/questions/2041575/…,之间不需要
  • 这里的大多数人都希望样本表数据和预期结果为格式化文本,而不是图像。 (而且我无法阅读那个微小的图像文本......)
  • 您应该考虑在整个数据库中使用更一致的命名约定。例如,如果表名为laces_users_profile,则订单应该有laces_user_profile_id 或其他名称,而不是customer_id。或者您应该调用laces_users_profilecustomers
  • 如果我今天添加客户怎么办?我也将被视为客户在过去 30 天内未下订单。它不应该发生。最近添加的客户不应出现在最近 30 天内未下订单的客户列表中。如何达到那个条件。 @BadHorsie

标签: php mysql sql


【解决方案1】:

您可以使用left join 反模式:

select u.*
from laces_users_profiles u
left join laces_order o
    on o.customer_id = u.laces_user_id 
    and o.create_date > now() - interval 30 day
where o.customer_id is null

使用not exists 条件和相关子查询可以获得相同的结果:

select u.*
from laces_users_profiles u
where not exists (
    select 1
    from join laces_order o
    where 
        o.customer_id = u.laces_user_id 
        and o.create_date > now() - interval 30 day

)

【讨论】:

  • 谢谢!! @GMB 它的工作!
  • 如果我今天添加客户怎么办?我也将被视为过去 30 天内未下订单的客户。它不应该发生。最近添加的客户不应出现在最近 30 天内未下订单的客户列表中。如何达到那个条件。 @GMB
猜你喜欢
  • 2016-02-09
  • 2019-01-14
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多