Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql equivalent of IN() clause doing logical AND's instead

Tags:

mysql

Let's say I have a table making a junction between two tables... like this:

id_product | id_category
-----------------
11 | 22
11 | 33
12 | 22
12 | 33

I want to get id_products (distinct) according to a list of searched categories IDs.

If I use the IN() clause, the list of id_categories uses a logical OR.

How can I make a SELECT query to have logical ANDs for the list of id_categ submitted??

Example: I want all the id_products belonging to category 22 AND 33 (and possibly 5+ more Categ. IDs)

I found this answer: Using MySQL IN clause as all inclusive (AND instead of OR) ...but the query is mixing more than 1 table... I only want a query on a single table, the junction one.

like image 476
ecchymose Avatar asked Aug 15 '12 20:08

ecchymose


People also ask

What does && mean in MySQL?

MySQL logical AND operator compares two expressions and returns true if both of the expressions are true. Syntax: AND, && This operator returns 1 if all operands are nonzero and not NULL, 0 if one or more operands are 0, otherwise, NULL is returned.

What are the logical operators we have in MySQL and or not && || none of the above?

In SQL, all logical operators evaluate to TRUE , FALSE , or NULL ( UNKNOWN ). In MySQL, these are implemented as 1 ( TRUE ), 0 ( FALSE ), and NULL . Most of this is common to different SQL database servers, although some servers may return any nonzero value for TRUE .

Why in clause is used in MySQL?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

How do you write not equal to in MySQL?

not equal to (<>, !=) operator. MySQL Not equal is used to return a set of rows (from a table) after making sure that two expressions placed on either side of the NOT EQUAL TO (<>) operator are not equal.


2 Answers

reading your link, I think it would be something like

select id_product 
from yourTable
where id_category in (--your List goes Here)
group by id_product 
having count(distinct id_category) = NumberOfElementsOfYourList

you should use = if only wants to get that id_category, but no others id_category. If not, use >=

like image 189
Gonzalo.- Avatar answered Oct 21 '22 03:10

Gonzalo.-


select id_product
from your_table
where id_category in (22, 33)
group by id_product
having count(distinct id_category) = 2

You can add a having clause that counts the found id_category's. If you look for 5 IDs for instance, you have to change the 2 in 5 in the having clause.

like image 39
juergen d Avatar answered Oct 21 '22 02:10

juergen d