简体   繁体   English

如何检查sql中Where In子句中存在的所有数组元素

[英]How to check all array elements exists in Where In Clause in sql

I am facing one problem for creating one sql query.我在创建一个 sql 查询时遇到了一个问题。 Actually i want to check if wherein clause Exists all elements or not, If all elements exists in WhereIn clause then i want to return that records with groupby.. Here is my one table produt_categories :-实际上我想检查 where 子句是否存在所有元素,如果所有元素都存在于 WhereIn 子句中,那么我想用 groupby 返回该记录..这是我的一个表 produt_categories :-

id product_id  category_id
 1    1              1
 2    1              2

Sow when i apply Wherein Like below:-当我申请时播种,如下所示:-

SELECT * FROM `product_categories` 
WHERE  category_id in (1,2,3) group by(product_id);

Now it return me this result:-现在它返回给我这个结果:-

id product_id  category_id
 1    1              1

Actually its returning me fine because actual behavior of whereIn clause.实际上它让我很好,因为 whereIn 子句的实际行为。 So i want if all category_id 1,2,3 exists then it must show records.所以我想要如果所有 category_id 1,2,3 都存在,那么它必须显示记录。 If i pass 1,2 then i will also come.如果我通过 1,2,那么我也会来。 Hope you guys understand.Please help me to create qyuery希望你们理解。请帮我创建qyuery

You could use HAVING :你可以使用HAVING

SELECT * 
FROM `product_categories` 
WHERE  category_id in (1,2,3) 
group by(product_id)
HAVING COUNT(DISTINCT category_id) = 3;  -- #elements from `IN` clause

SELECT * FROM tab GROUP BY col is an anti-pattern. SELECT * FROM tab GROUP BY col是一种反模式。

Related article: Group by clause in mySQL and postgreSQL, why the error in postgreSQL?相关文章: mySQL 和 postgreSQL 中的 Group by 子句,为什么 postgreSQL 会出错?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM