我陷入了一个与 MySQL 相关的问题。已采取的查询
select * from orders where customer_id in (256, 255, 236);
在各个网站上,在 IN 运算符的解释下,他们提到(例如 https://www.w3schools.com/sql/sql_in.asp )IN 的作用就像多个 OR 条件的快捷方式。
MySQL中是否有用于多个AND条件的运算符?
上面的查询将返回与 customer_id 256、255 和 236 相关的所有行。但是,如果我只想返回这三个 customer_id 共有的行,我尝试了以下查询。
select * from orders where customer_id = 256 and customer_id = 255 and customer_id = 236;
但我知道这是行不通的。
所以我想知道是否可以对多个 AND 条件使用快捷方式(不使用 group by 和having)?
最佳答案
您可以使用聚合:
select o.order_id
from orders o
where o.customer_id in (256, 255, 236)
group by o.order_id
having count(distinct o.customer_id) = 3; -- "3" = all customers
这需要聚合(或连接
或窗口函数),因为您想要比较不同行上的数据。在这种情况下,简单的 WHERE
子句是不够的。
关于mysql - 如果 'IN' 是多个 'OR' 的快捷方式,那么 MySQL 中多个 'AND' 的快捷方式可以是什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58201327/