首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于返回没有活动组成员身份的用户的SQL查询

问用于返回没有活动组成员身份的用户的SQL查询
EN

Stack Overflow用户
提问于 2021-04-14 06:30:14
回答 1查看 18关注 0票数 0

我有这个模式,它可以软删除/归档一个组:

代码语言:javascript
复制
create table users (id int, name varchar(255));
create table groups (id int, name varchar(255), archived_at datetime);
create table memberships (group_id int, user_id int);

insert into users (id, name) values 
  (1, 'no groups'),
  (2, 'only active groups'),
  (3, 'only archived groups'),
  (4, 'active and archived groups');

insert into groups (id, name, archived_at) values
  (1, 'active group', null),
  (2, 'archived group', '2021-04-13');

insert into memberships (user_id, group_id) values
  (2, 1),
  (3, 2),
  (4, 1),
  (4, 2);

我想查询那些“没有组”的用户:恰好是零个活动(非归档)组,加上零个或多个归档组。

代码语言:javascript
复制
-- How do I get this to return only users 1 and 3?
select *
from users u
left join memberships m on m.user_id = u.id
left join groups g on g.id = m.group_id
where
  m.group_id is null
  or 
  g.archived_at is not null

对于当前的模式,这是可能的吗?

https://www.db-fiddle.com/f/h1szvQmQHp1g84Ex9WvRHy/1

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-14 06:32:44

这听起来像not exists

代码语言:javascript
复制
select u.*
from users u
where not exists (select 1
                  from memberships m join
                       groups g
                       on m.group_id = g.id
                  where m.user_id = u.id and g.archived_at is null
                 );

据推测,活动组是尚未存档的组。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67083198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档