Sitemap
Boris Sadkhin

Boris Sadkhin

Recurse Center Alum. DevOps team lead at KBase.us (Argonne National Laboratory)

SQL Join Wizardry

1 min readSep 20, 2017

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

    Get Boris Sadkhin’s stories in your inbox

    Join Medium for free to get updates from this writer.

  1. to load the products I want, and then to query the database again for each product to get its specifications..
  2. create a temporoary table of specifications, which contains the specifications for each product (HUUGE!)
  3. Group_concat the specifications and then parse the string

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.

--

--

Boris Sadkhin
Boris Sadkhin

Written by Boris Sadkhin

Recurse Center Alum. DevOps team lead at KBase.us (Argonne National Laboratory)