SQL IN 和 AND 子句输出

标签 sql

我写了一个像下面这样的小查询。它正在给我输出。

select user_id 
from table tf
where tf.function_id in ('1001051','1001060','1001061')

但是当我像下面这样运行查询时,它显示 0 输出。但是我手动验证了我们有 user_id,其中所有 3 个 function_id 都存在。

select user_id 
from table tf
where tf.function_id='1001051' 
      and 
      tf.function_id='1001060' 
      and 
      tf.function_id='1001061'

使用AND子句看起来很简单。但是我没有得到想要的输出。我做错了什么吗?

提前致谢

最佳答案

这是你想做的吗?

select tf.user_id
from table tf
where tf.function_id in ('1001051', '1001060', '1001061')
group by tf.user_id
having count(distinct tf.function_id) = 3;

这将返回具有所有三个功能的用户。

编辑:

这是您评论中的查询:

select tu.dealer_id, tu.usr_alias, tf.function_nm
from t_usr tu, t_usr_function tuf, t_function tf
where tu.usr_id = tuf.usr_id and tuf.function_id = tf.function_id and
      tf.function_id = '1001051' and tf.function_id = '1001060' and tf.function_id = '1001061' ;

首先,您应该学习正确的 join 语法。简单规则:永远不要在 from 子句中使用逗号。

我认为你想要的查询是:

select tu.dealer_id, tu.usr_alias
from t_usr tu join
     t_usr_function tuf
     on tu.usr_id = tuf.usr_id 
where tuf.function_id in ('1001051', '1001060', '1001061')
group by tu.dealer_id, tu.usr_alias
having count(distinct tuf.function_id) = 3;

这不会为您提供函数名称。如果每个“用户”(或至少是经销商/用户别名组合)都具备所有三个功能,我不确定为什么需要这样的详细信息。而且,原始问题不要求这种详细程度。

关于SQL IN 和 AND 子句输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726108/

相关文章:

mysql - 在搜索查询中包含自定义字段

c# - 从C#调用Azure SQL存储过程非常慢

sql - 如何在单个 ALTER TABLE 中添加和删除列

mysql - 将 sql 查询结果的前 4 个字符分配到另一列?

mysql - SQL触发器语句错误

mysql - 如何减慢我的查询速度

mysql - col 查询结果中有重复字段

sql - 将两个表,多行合并成一行不同的列

mysql - SQL 连接具有一对多关系 - 将多个关系合并为一行?

MySQL 问题 - 我想删除任何括号内的所有文本