[Solved] how to JOIN table with WHERE clause and also show non existent rows

EverSQL Database Performance Knowledge Base

how to JOIN table with WHERE clause and also show non existent rows

The title may sound a bit confusing, but let me explain:
I have three tables:
store

storeID | name
1       | store1
2       | store2
3       | store3

product

productID | name
1         | ball
2         | cup

store_product

storeID_fk | productID_fk
2          | 1
1          | 2
3          | 2

What I want to archive is a result like the following:

storeID | name  | storeID_fk | productID_fk
1       | store1| NULL       | NULL
2       | store2| 2          | 1
3       | store3| NULL       | NULL

What I have tried so far:

SELECT * FROM `store` 
LEFT JOIN `store_product` on storeID = storeID_fk  
WHERE productID_fk = 1;

But this only returns:

storeID | name  | storeID_fk | productID_fk
2       | store2| 2          | 1

How can I also display the empty/not existing rows?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
The optimized query:
SELECT
        * 
    FROM
        `store` 
    LEFT JOIN
        `store_product` 
            ON storeID = storeID_fk 
    WHERE
        productID_fk = 1

Related Articles



* original question posted on StackOverflow here.