Here’s my problem: I have three tables that represent a many to many relationship which look like to following:
table products
product_id
product_price, etc. (basic info same for every product)
table specifications
spec_id
spec_name
table products_specifications
product_id
spec_id
content
My goal is to select products by their specifications (one as well as multiple) so I used the following query:
SELECT *
FROM products p
JOIN products_specifications ps ON ps.products_id = p.products_id
JOIN specifications s ON s.spec_id = ps.spec_id
WHERE s.spec_name IN (<names of specs>)
AND pts.content IN (<content of specs>)
GROUP BY p.products_id
HAVING COUNT(DISTINCT s.specifications_name) = <count of specs name>
AND COUNT(DISTINCT ps.content) = <count of specs content>
I would like to get ALL of the specifications that belong to ALL products, however this query only returns one of the specifications (one that is used to make the query).
The specifications.content column contains the values that I want to use to query a product (or multiple) with (included with all it’s specifications). The name of these specifications can be found specifications.spec_name table. To make sure the query does not retrieve content that is possibly the same in another row but from a different specification I also do a WHERE IN of the names of the specifications.
Is it possible make a query that selects on certain specifications, but also returns ALL specifications of the selected product?
I have thought of and experimented with UNIONS and SUBQUERIES. However I wasn’t able to produce a query that sufficed. I think a subquery is probably the direction to go in. A second query with the returned product_id is not a possiblity, because it has to be possible to order the query by ANY of the specifications belonging of each product.
Your query seems correct. It will return all products’ details for those products that match your criteria (they are realted to all
(<names of specs>)and all(<content of specs>)). It would be better to useSELECT p.*by the way, since you are grouping byp.products_id. The results you get from the other columns are not really useful.Now, if you want to get these products and in addition, get all specifications for these products (not only the spcs that are in your two lists), use this:
(update: Added
GROUP BY pd.products_idandGROUP_CONCAT()to gather info for a product from many rows into one)