M
M
madc0de2019-06-03 20:09:12
SQL
madc0de, 2019-06-03 20:09:12

How to generate such sql query?

Good afternoon!

SELECT * FROM oc_product WHERE product_id IN (
SELECT * FROM oc_product_to_category WHERE category_id IN (
SELECT category_id FROM oc_product_to_category WHERE product_id = '1'
)
) limit 6

How to write such sql query correctly. And most importantly, fast, without unnecessary load on the database
1) We get the product category ID from table 1
2) We take from the same table all products with the given category ID
3) We take all products from table 2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BorLaze, 2019-06-03
@madc0de

So write.
Only in subqueries it is not necessary to pull out all the fields, but only the id:

SELECT * FROM oc_product 
WHERE product_id IN (
    SELECT product_id FROM oc_product_to_category 
    WHERE category_id IN (
        SELECT category_id FROM oc_product_to_category 
        WHERE product_id = '1'
    )
) 
LIMIT 6

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question