I have following two MySQL tables
every product can have multiple sizes
I need to make a query that
What I have now the query below. I works but doesn't constrain by category and only returns the one size specified (here '10') - I need all sizes, but only for the products that have '10' among its sizes...
SELECT products.*
, products_sizes.*
FROM (
SELECT *
FROM products
LIMIT $limit OFFSET $offset
) AS products
LEFT JOIN products_sizes
ON products.products_id = products_sizes.products_id
WHERE products_sizes.size = 10
... and if I add WHERE category = 'something' query returns nothing...
SELECT products.*
, products_sizes.*
FROM (
SELECT *
FROM products
WHERE category = 'shoes'
LIMIT $limit OFFSET $offset
) AS products
LEFT JOIN products_sizes
ON products.products_id = products_sizes.products_id
WHERE products_sizes.size = 10
??
UPDATE: getting closer...
After reading the answers I now have this:
SELECT *
FROM products AS p
LEFT JOIN products_sizes AS s
ON p.product_id = s.product_id
WHERE s.product_id
IN (SELECT product_id FROM s WHERE size = 10)
AND p.category = 'shoes'
It satisfies my initial question's first two requirements:
... BUT I still need to limit the results to a certain number of products. If I put a LIMIT $limit at the very end of the query, it will limit the number of sizes returned and not the number of products... Thanks for the input.
The WHERE
clause in your main query is defeating the purpose of your LEFT JOIN
, making it the same as an INNER JOIN
. It's very possible that there are not any rows selected by your derived table that match (shoes of size 10).
Unless there is something about your data not shown, you can try this:
SELECT products.*
, products_sizes.*
FROM products
JOIN products_sizes
ON products.products_id = products_sizes.products_id
WHERE products.category = 'shoes'
AND products_sizes.size = 10
LIMIT $limit OFFSET $offset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With