干得好。(确保你有正确的索引)。另请注意,我离开了原始联接,因为我假设您在某些时候需要的不仅仅是 member_id。但是如果你想要的只是 member_id,你可以一起删除 members 表。
/*
insert members (member_name) values ('tom')
insert members (member_name) values ('bob')
insert members (member_name) values ('jim')
declare @tom int
set @tom = (select member_id from members where member_name = 'tom')
insert subscriptions (member_id, is_active) values (@tom, 1)
insert subscriptions (member_id, is_active) values (@tom, 0)
declare @bob int
set @bob = (select member_id from members where member_name = 'bob')
insert subscriptions (member_id, is_active) values (@bob, 0)
insert subscriptions (member_id, is_active) values (@bob, 0)
*/
SELECT m.member_id
FROM members as m
INNER JOIN subscriptions as s ON s.member_id = m.member_id
LEFT JOIN subscriptions s2 on s2.member_id = m.member_id and s2.is_active = 1
WHERE
s.is_active = 0 and
s2.subscription_id is null
Group By m.member_id
或者
SELECT s.member_id
FROM subscriptions as s
LEFT JOIN subscriptions s2 on s2.member_id = s.member_id and s2.is_active = 1
WHERE
s.is_active = 0 and
s2.subscription_id is null
Group By s.member_id