【问题标题】:SQL query with multiple OR condition inside AND returns null or empty在 AND 内具有多个 OR 条件的 SQL 查询返回 null 或空
【发布时间】:2021-04-05 15:42:51
【问题描述】:

我试图让那些将符合我的过滤条件的成员,但我在圆括号内传递了多个 OR 条件,并且圆括号内的每个条件都是,并且带有另一个圆括号;但是,查询不起作用,它返回一个空表,但是每当我使用 INTERSECT 语句运行查询时,它都会返回成员。尽管如此,100 万条记录已经花费了 3 秒,而且在服务器端这是一个非常昂贵的操作,如果记录增加,它会增加。有人可以帮我为什么我的第一个查询不起作用,或者如果我使用第二个查询,有什么办法可以缩短时间吗?

我的实际表

第一个查询,返回空表

SELECT custom_attribute_values.attributable_id as Member_id FROM custom_attribute_values
WHERE (("custom_attribute_id" = '12' AND "value_string" = 'Female') OR ("custom_attribute_id" = '12' AND "value_string" = 'Male'))
AND (("custom_attribute_id" = '17' AND "value_string" = 'Widowed') OR
("custom_attribute_id" = '17' AND "value_string" = 'Divorced') OR ("custom_attribute_id" = '17' AND "value_string" = 'Never married') OR
("custom_attribute_id" = '17' AND "value_string" = 'Married') OR ("custom_attribute_id" = '17' AND "value_string" = 'Separated'))

第二个查询,返回结果,我对此很感兴趣,但花费了太多时间

SELECT custom_attribute_values.attributable_id FROM custom_attribute_values
WHERE (("custom_attribute_id" = '12' AND "value_string" = 'Female') OR ("custom_attribute_id" = '12' AND "value_string" = 'Male'))
INTERSECT
SELECT custom_attribute_values.attributable_id FROM custom_attribute_values WHERE (("custom_attribute_id" = '17' AND "value_string" = 'Widowed') OR
("custom_attribute_id" = '17' AND "value_string" = 'Divorced') OR ("custom_attribute_id" = '17' AND "value_string" = 'Never married') OR
("custom_attribute_id" = '17' AND "value_string" = 'Married') OR ("custom_attribute_id" = '17' AND "value_string" = 'Separated'))

【问题讨论】:

    标签: sql postgresql query-optimization


    【解决方案1】:

    每一行都有相互冲突的条件。我很确定你想要聚合:

    SELECT cav.attributable_id as Member_id
    FROM custom_attribute_values cav
    WHERE ("custom_attribute_id" = '12' AND "value_string" IN ('Female', 'Male')) OR 
          ("custom_attribute_id" = '17' AND "value_string" IN ('Widowed', 'Divorced', 'Never married', 'Married', 'Separated')
          )
    GROUP BY cav.attributable_id
    HAVING COUNT(DISTINCT "custom_attribute_id") = 2;  -- both match
    

    WHERE 检查任一条件是否匹配。 HAVING 验证两者都与给定成员匹配。

    请注意,标识符应避免使用双引号。它们只是使查询更难编写和阅读。

    【讨论】:

    • 谢谢,但我想在 AND 而不是 OR WHERE ("custom_attribute_id" = '12' AND "value_string" IN ('Female', 'Male')) AND ("custom_attribute_id " = '17' AND "value_string" IN ('Widowed', 'Divorced', 'Never mapped', 'Married', 'Separated') ) 像这样请你帮我看看怎么可能谢谢
    • @Adnan 。 . .你错过了重点。 HAVING 子句的核心是确保两个条件在成员 ID 上都匹配。
    • 您的意思是 HAVING 子句必须满足我使用的或 WHERE 子句中的两个条件?对
    • @Adnan 。 . . WHERE 子句将所有可能的行过滤到许多 any 条件的行。 HAVING 选择的成员 ID 具有 both 对成员有效的条件 -- 尽管在不同的行中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多