M
M
Mikhail Nosov2012-04-09 13:15:35
MySQL
Mikhail Nosov, 2012-04-09 13:15:35

Link table. Selecting object_id values ​​whose option_id is equal to several values ​​at the same time

There is a link table:

CREATE TABLE `object_option` (
`object_id` int(11) NOT NULL,
`option_id` int(11) NOT NULL
PRIMARY KEY (`object_id`,`option_id`)
)

You need to select from the table such object_id, option_id of which are equal to several values ​​at the same time.

Example:

object_id option_id
one one
one 2
one 3
2 one
3 3

You need to select object_id whose option_id is 1 and 2.

How to do it in MySQL? ;)

PS At first glance, everything is very simple, but for some reason it does not work ...

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vitaly Peretyatko, 2012-04-09
@viperet

SELECT object_id FROM object_option WHERE option_id IN (1, 2)

S
Sergey, 2012-04-09
@Ualde

First, how can there be two primary keys?
Secondly, no matter how much I searched for a catch, I did not find it:
select * from `object_option` where `object_id` in(1, 2) and `option_id` in(1, 2);

E
egorinsk, 2012-04-09
@egorinsk

SELECT fields FROM table WHERE option_id IN (1,2) UNION SELECT fields FROM table WHERE object_id IN (1,2)
This approach allows you to use indexes (if any) instead of iterating over all table rows (when using OR)

U
uoYkcuF, 2012-04-10
@uoYkcuF

>It is necessary to select such object_id from the table, option_id of which are equal to several values ​​at the same time.
select o.object_id as object_id
from object_option o
INNER JOIN object_option o2 on o2.object_id = o.object_id
WHERE o2.option_id != o.option_id
GROUP BY o.object_id

G
grefon, 2015-11-09
@grefon

Now there is a similar issue. Did you happen to find a solution?
It occurred to me only to process the request through the tempo function:
It turns out that we combine all the options of the object into a group and get the temp variable. Next, we compare this variable with the set of options we need. If you have found a more delicate solution, then please share))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question