【问题标题】:Filter self joined and include only rows that dont match nested join过滤自联接并仅包含与嵌套联接不匹配的行
【发布时间】:2020-10-06 09:57:56
【问题描述】:
我有以下伪表:(PostgresSQL)
Payment
id: number;
groupId: number;
status: [Pending|Executed];
PaymentLog
id: number;
paymentId: number;
date: Date; // YYYY-DD-MM
- 获取所有
Payment 和Pending
- 但如果
PaymentLog 中的一行引用同一groupId 下的Payment 并匹配特定date,则排除Payment
我尝试过类似的东西
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 的项目,这也会匹配。
【问题讨论】:
标签:
sql
postgresql
subquery
left-join
where-clause
【解决方案1】:
我怀疑你想要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'
)
【解决方案2】:
我会在 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')
【解决方案3】:
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