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.
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.
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 .
The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.
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.
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 >=
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With