【问题标题】:Treat WHERE IN parameters as AND and not OR将 WHERE IN 参数视为 AND 而不是 OR
【发布时间】:2017-12-07 20:14:19
【问题描述】:

我有这个表结构/数据:

我想选择在 (attribute_id,store_id 上具有 (97,6,2) AND (99,1,4) 组合的 row_id(s) ,value)。

在这个例子中,我们想要得到row_id 8664,因为它尊重这个条件。

我所做的是使用where in 语句,如下所示:

SELECT DISTINCT row_id from catalog_product_entity_int 
where row_id in 
   (select row_id from catalog_product_entity_int 
    WHERE (attribute_id, store_id,value) 
    IN ( (99,1,4),(97,6,1) ))

这将输出具有 (99,1,4) OR (97,6,1) 的行。

我试过这个查询:

SELECT DISTINCT row_id from catalog_product_entity_int 
where row_id in 
    (select row_id from catalog_product_entity_int 
    WHERE (attribute_id, store_id,value) IN (99,1,4) 
    AND (attribute_id, store_id,value) IN(97,6,1) )

但我有#1241 - Operand should contain 3 column(s)

我如何设法选择同时验证这两个条件的行?

【问题讨论】:

    标签: mysql sql where-in


    【解决方案1】:

    这很容易。

    向量 (99, 1, 4)(97, 6, 1) 必须放在括号中:((99, 1, 4))((97, 6, 1))

    试试:

    SELECT DISTINCT row_id 
    FROM catalog_product_entity_int 
    WHERE row_id IN (
        SELECT row_id 
        FROM catalog_product_entity_int 
        WHERE (attribute_id, store_id, value) IN ((99, 1, 4))
              OR (attribute_id, store_id, value) IN ((97, 6, 1))
    )
    

    甚至更好:

    SELECT DISTINCT row_id 
    FROM catalog_product_entity_int 
    WHERE row_id IN (
        SELECT row_id 
        FROM catalog_product_entity_int 
        WHERE (attribute_id, store_id, value) IN ((99, 1, 4), (97, 6, 1))
    )
    

    【讨论】:

    • 当然,你是对的@FabianPijcke,谢谢。我纠正了这一点。
    【解决方案2】:

    像这样写出你的 where 条件

    WHERE (attribute_id = 99 AND store_id = 1 AND value = 4)
    OR (attribute_id = 99 AND store_id = 6 AND value = 1)
    

    【讨论】:

      【解决方案3】:

      试试:

      SELECT DISTINCT row_id FROM catalog_product_entity_int WHERE row_id IN 
      (SELECT row_id FROM catalog_product_entity_int 
      WHERE (attribute_id = 99 AND store_id = 1 AND value = 4)
      OR (attribute_id = 97 AND store_id = 6 AND value = 1))
      

      【讨论】:

      • 和WHERE IN一样,我喜欢两个条件之间有AND
      • 你试图强加的 WHERE 条件是安静不可行的。根据您的情况,单个记录可以同时具有 attribute_id 99 和 97,这是不合逻辑的。
      猜你喜欢
      • 2014-07-13
      • 2010-10-30
      • 2019-10-31
      • 2022-01-07
      • 2014-05-11
      • 1970-01-01
      • 2017-12-04
      • 2012-10-15
      • 1970-01-01
      相关资源
      最近更新 更多