SQL Join Wizardry
So at work I had to get a list of products. Then for each products, I wanted to collect its specifications from a different specifications database.. And those specifications are located in rows, not in columns
What I want
+---------+--------+--------+
| Product | Gender | Color |
+---------+--------+--------+
| Shirt | Male | Blue |
| Shirt | Male | Green |
| Shirt | Female | Purple |
+---------+--------+--------+Specifications Table
+---------------+-----------------+
| Specification | SpecificationID |
+---------------+-----------------+
| Gender | 10001 |
| Color | 10002 |
+---------------+-----------------+
The solutions I thought of were
- to load the products I want, and then to query the database again for each product to get its specifications..
- create a temporoary table of specifications, which contains the specifications for each product (HUUGE!)
- Group_concat the specifications and then parse the string
Get Boris Sadkhin’s stories in your inbox
Join Medium for free to get updates from this writer.
But a coworker suggested, why not use multiple joins:
SELECT ProductID,spec1.value,spec2.value FROMLEFT JOIN specifications spec1 ON
product.specificationID = specification.specificationID where spec1.specificationID = 10001
LEFT JOIN specifications spec2 ON
product.specificationID = specification.specificationID where spec2.specificationID = 10002
I hadn’t thought of that.





