Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: IN statement equivalent for logical AND

Tags:

sql

I currently use a software where there are relations between objects and tags in a SQL table as below:

+-----------+--------+
| object_id | tag_id |
+-----------+--------+
|       226 |     31 |
|       226 |     35 |
|       313 |     31 |
|       312 |     35 |
+-----------+--------+

Getting all the object ids for a list of tag ids with a logical OR is fine with the following request:

select distinct object_id from tags_link where tag_id in (31, 35);

How can all the object ids for a list of tag ids with a logical AND can be obtained?

For the above table, a request for tag ids 31 and 35 should only return object_id 226.

like image 206
Eric Avatar asked Jan 21 '26 11:01

Eric


1 Answers

select object_id
from tags_link
where tag_id in (31,35)
group by object_id
having count(distinct tag_id) = 2

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!