简体   繁体   English

如何从table_a中选择记录,如果table_b中与table_a相连的记录有一定的值

[英]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:我在 MySQL 中有两个表:
products产品

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

and products_metaproducts_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? 1. 我需要什么?
I need to select all products from products table, when each product has 'status' = 'enabled' and 'availability' > 0 in table products_meta .我需要从products表中选择所有产品,当每个产品在表products_meta中具有'status' = 'enabled''availability' > 0时。

2. My ideas 2. 我的想法

  • Do something like做类似的事情
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但我不完全知道,如何还要求其他键大于 0

products_meta.key = 'availability' AND products_meta.value > 0
  • Or use join method, like或者使用 join 方法,比如
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 3. 期望的结果
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 匹配的所有记录
products_meta 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.我查看了很多关于 Stack Overflow 的问题,但找不到符合我需求的示例。

I would use an aggregation approach on the products_meta table here along with a join:我将在products_meta表上使用聚合方法以及连接:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM