G
G
Gopa2020-05-29 19:19:52
MySQL
Gopa, 2020-05-29 19:19:52

How to write mysql query?

5ed134bf8bc4c396783027.png
There is a table with product_id and filter-value id. The site has a filter. When filtering, we get an array of id filter-values.
How to get all product_ids that have all value filter ids.

For example, how to get the product_id, where the av_id column contains the values ​​3,11,15. In the case like in the picture, product_id = 87 will be returned.
And if there are values ​​of 2.3, then product_id = 87 and product_id = 305 will be returned.

Or maybe there is a more optimal structure?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
Lazy @BojackHorseman MySQL, 2020-05-29
Tag

3 times exists
or 3 times join
look at the plan, choose the optimal one

D
d-stream, 2020-05-29
@d-stream

in the case of all id - you can How to make a SQL query on three tables?

K
Konstantin Tsvetkov, 2020-05-29
@tsklab

SELECT product_id FROM 
(
SELECT product_id FROM T WHERE av_id = 3
UNION ALL
SELECT product_id FROM T WHERE av_id = 11
UNION ALL
SELECT product_id FROM T WHERE av_id = 15
) AS F
GROUP BY product_id
HAVING COUNT(*) = 3

SELECT product_id FROM 
(
SELECT product_id FROM T WHERE av_id = 3
UNION ALL
SELECT product_id FROM T WHERE av_id = 2
) AS F
GROUP BY product_id
HAVING COUNT(*) = 2

D
Dmitry Gordinskiy, 2020-05-29
@DmitriyGordinskiy

SELECT product_id
FROM table_name
WHERE av_id IN (3, 11, 15)
GROUP BY product_id 
HAVING COUNT(DISTINCT av_id) = 3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question