gpt4 book ai didi

mysql - SQL查询丢弃具有多个条目的记录

转载 作者:行者123 更新时间:2023-11-29 21:41:52 25 4
gpt4 key购买 nike

我正在尝试查找查询来解决我的问题:

我的数据库中有这样的内容:

enter image description here

我需要一个查询来选择具有角色 5 的所有用户,但如果由于某种原因他们具有任何其他角色,则应该跳过它们

SELECT user_id FROM user_table WHERE roleid = 5 AND (roleid != 3 OR roleid != 1)

仍然返回用户 64

最佳答案

我认为您正在寻找一个不存在子句:

select *
from t
where roleid = 5 and
not exists (select 1
from t t2
where t2.user_id = t.user_id and t2.roleid <> 5
);

或者,如果您只是寻找此类用户,那么您可以使用 group byhaving:

select user_id
from t
group by user_id
having min(roleid) = max(roleid) and min(roleid) = 5;

(如果 roleid 可能是 NULL,逻辑需要考虑到这一点。)

关于mysql - SQL查询丢弃具有多个条目的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34427093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com