Matthew
Matthew

Reputation: 59

How to select records from table_a, if in table_b records connected with table_a has a certain value

I have two tables in MySQL:
products

id | created_at | updated_at
----------------------------
1  | 10-06-2022 | 11-06-2022
2  | 9-06-2022  | 11-06-2022

and products_meta

id | product_id | key          | value
-----------------------------------------
1  | 1          | status       | enabled
2  | 1          | availability | 50
3  | 1          | name         | Bike
4  | 2          | status       | disabled
5  | 2          | availability | 25
6  | 2          | name         | Rollers

etc.

1. What do I need?
I need to select all products from products table, when each product has 'status' = 'enabled' and 'availability' > 0 in table products_meta.

2. My ideas

SELECT products.id FROM products WHERE products.id in (SELECT products_meta.product_id FROM products_meta WHERE products_meta.key = 'status' AND products_meta.value = 'enabled')

but I don't exactly know, how to also require other key to be greater than 0

products_meta.key = 'availability' AND products_meta.value > 0
SELECT products.id FROM products RIGHT JOIN products_meta WHERE (products_meta.key = 'status' AND products_meta.value = 'enabled')

and again, I don't know how to require other condition to be true

products_meta.key = 'availability' AND products_meta.value > 0

3. Desired result
I want to get from database result:
products

id | created_at | updated_at
----------------------------
1  | 10-06-2022 | 11-06-2022

and also all records from products_meta that matches product id that matches criteria
products_meta

id | product_id | key          | value
-----------------------------------------
1  | 1          | status       | enabled
2  | 1          | availability | 50
3  | 1          | name         | Bike

I looked through a lot of questions on Stack Overflow, and couldn't find example that matched my needs.

Upvotes: 0

Views: 53

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520928

I would use an aggregation approach on the products_meta table here along with a join:

SELECT p.*
FROM products p
INNER JOIN
(
    SELECT product_id
    FROM products_meta
    GROUP BY product_id
    HAVING MAX(CASE WHEN `key` = 'status' THEN value END) = 'enabled' AND
           MAX(CASE WHEN `key` = 'availability' THEN value END) > 0
) pm
    ON pm.product_id = p.id
ORDER BY p.id;

Upvotes: 1

Related Questions