繁体   English   中英

具有连接表的多个和条件

[英]Multiple and condition with joined table

我正在尝试在单个 MySQL 查询中查找记录,但如果您知道任何信息,我无法查看并帮助我。

products(Table 1)
id  | title
----------
1   | Test 1
2   | Test 2
3   | Test 3

nutritions (Table 2)
id | product_id | title    | evaluation(string)
-------------------------------
1  | 1          | calories | 8
2  | 3          | proteins | 5
3  | 3          | calories | 8
4  | 3          | Sugar    | 9
5  | 2          | calories | 8
6  | 2          | Sugar    | 9

我想对产品表应用过滤器,如下所示。

情况1:

(nutritions.title = 'calories' AND nutritions.evaluation = '8') and (nutritions.title = 'Sugar' AND nutritions.evaluation = '9')

案例2:

(nutritions.title = 'calories' AND nutritions.evaluation = '8') and (nutritions.title = 'Sugar' AND nutritions.evaluation = '9') and (nutritions.title = 'proteins' AND nutritions.evaluation = '5')

预期输出:

products(case 1)                       products(case 2)
id  | title                            id  | title
----------                            --------------
2   | Test 2                           3   | Test 3
3   | Test 3

我尝试了以下查询,但我有超过 70k 的产品需要时间。

Product.find_by_sql("
        select `products`.* from products 
            JOIN nutritions where products.id = nutritions.product_id 
                and (nutritions.title = 'calories' and nutritions.evaluation = '8') 
                and nutritions.product_id IN(
                        select product_id 
                        from nutritions 
                        where nutritions.title = 'Sugar' 
                        and nutritions.evaluation = '9'
                        )
            ")

有几种方法可以解决这个问题。 一种方法是使用exists

select p.*
from products p
where exists (select 1
              from nutritions n
              where n.product_id = p.id and
                    n.title = 'calories' and
                    n.evaluation = '8'
             ) and
      exists (select 1
              from nutritions n
              where n.product_id = p.id and
                    n.title = 'Sugar' and
                    n.evaluation = '9'
             ) ;

有了nutritions(product_id, title, evaluation)指数nutritions(product_id, title, evaluation) ,这应该有很好的表现。

基本上一列不能同时包含 2 个或更多的东西,我是指nutritions.title标题不能是caloriesSugar

所以不要使用 AND 使用 OR

    (nutritions.title = 'calories' AND nutritions.evaluation = '8') 
OR  (nutritions.title = 'Sugar' AND nutritions.evaluation = '9')

暂无
暂无

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

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