Answer the question
In order to leave comments, you need to log in
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 |
Answer the question
In order to leave comments, you need to log in
SELECT object_id FROM object_option WHERE option_id IN (1, 2)
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);
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)
>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
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 questionAsk a Question
731 491 924 answers to any question