过滤自连接并仅包含与嵌套连接不匹配的行

Filter self joined and include only rows that dont match nested join

我有以下伪表:(PostgresSQL)

Payment
    id: number;
    groupId: number;
    status: [Pending|Executed];

PaymentLog
    id: number;
    paymentId: number;
    date: Date; // YYYY-DD-MM

我试过

SELECT p1.id FROM Payment
JOIN Payment p2 ON p1.groupId = p2.groupId
LEFT JOIN PaymentLog p3 ON p2.id = p3.paymentId AND date = '2020-09-06'
WHERE
   p3.id IS NULL
GROUP BY p2.id

但是,如果 PaymentLog 在引用 Payment 时有与 groupId 匹配但与日期不匹配的项目,这也会匹配。

我怀疑你想要not exists:

select p.* 
from payment p
where status = 'Pending' and not exists (
    select 1
    from paymentlog pl1
    inner join payment p1 on p1.paymentid = pl1.paymentid
    where p1.groupid = p.groupid and pl1.date = date '2020-09-06'
)

我会在 NOT EXISTS 条件下执行此操作:

select p.id
from payment p
where p.status = 'Pending'
and not exists (select *
                from paymentlog log 
                  join payment p2 on log.paymentid = p2.paymentid
                where log.groupid = p.groupid
                  and p2.id <> p.id
                  and log."date" = date '2020-09-06')
with temp as (
SELECT p1.id FROM Payment
JOIN Payment p2 ON p1.groupId = p2.groupId
--Were....
--group here if needed. or DISTINCT(p1.id)

)

select id from temp t
LEFT JOIN PaymentLog p3 ON t.id = p3.paymentId 
WHERE
date = '2020-09-06' and  p3.id IS NULL