连接同一表的postgresql复杂查询

连接同一表的postgresql复杂查询,postgresql,Postgresql,我想从“交易”表中获取这些客户,该表在过去6个月内没有创建任何交易 表: 'transactions' id, email, state, paid_at 想象: |------------------------ time period with all transactions --------------------| |-- period before month transactions > 0) ---|---- curr month transactions = 0 -|

我想从“交易”表中获取这些客户,该表在过去6个月内没有创建任何交易

表:

'transactions'
id, email, state, paid_at
想象:

|------------------------ time period with all transactions --------------------|
|-- period before month transactions > 0) ---|---- curr month transactions = 0 -|
我想这是可行的,连接只显示那些在右侧没有任何事务的连接

例如: 月份=11月

左侧的条件应为: COUNTl.id>0 l、 付款日期<'2013-05-01 00:00:00' 右侧的条件: COUNTr.id=0 r、 在“2013-05-01 00:00:00”和“2013-11-30 23:59:59”之间支付 加入是正确的方法吗

答复
有几种方法可以做到这一点。使用子查询获取过去6个月内交易的不同客户id,然后选择其id不在子查询中的客户

select c.id, c.name
from customer c
where c.id not in (select distinct customer_id from transaction where dt between <start> and <end>);
或者,使用从客户到事务的左联接,并过滤结果以使事务id为null。左侧联接包括左侧表中的所有行,即使右侧表中没有匹配的行也是如此。此处对左连接的说明:


左连接方法可能会更快。

感谢您的提示。我在原始PSOT中发布了我的最终查询。在pgsql 8.0/8.1之前的旧版本上,左连接速度明显更快,但在新版本上,子选择几乎迎头赶上。当然,在你测试之前,你不能确定。@Wilberforce。我认为distinct在第一个查询中是多余的。你是对的,它不会改变结果,但我认为它更容易理解-你可以剪切并粘贴子查询,然后单独运行它。它还可能对执行时间产生影响,尽管这可能是任意一种情况,具体取决于实现。
select c.id, c.name
from customer c
where c.id not in (select distinct customer_id from transaction where dt between <start> and <end>);
select c.id, c.name
from customer c
    left join transaction t on c.id = t.customer_id
          and t.dt between <start> and <end>
where t.id is null;