【问题标题】:How to use OR in Where clause when one of its field have null value?当其中一个字段具有空值时,如何在 Where 子句中使用 OR?
【发布时间】:2014-07-11 09:32:12
【问题描述】:

我正在尝试简单地查询数据,

select * from product where (color='blue' or type='suv')

我想要查询中提到的任何具有“颜色”和“类型”的特定数据,但如果我没有提到他的“类型”,那么它将仅从“颜色”获取数据。

例如:

product    color   type 
toyota      red     suv
honda       black   

select * from product where (color='blue' or type Is null)

在第二个查询中,它同时返回“toyota”和“honda”。

如果我给出它的“颜色”值,我需要获取产品,然后它只按颜色返回数据,如果我给出它的“颜色”和“类型”值,然后根据这两个值返回数据?

【问题讨论】:

  • 需要更多信息。如果您只想要color = 'blue',则将type 排除在where 子句之外。反之亦然。
  • 基本信息必须在question中,而不仅仅是cmets。请编辑您的问题。另外:In second query it return me both "toyota" and "honda". 这与显示的数据相矛盾。请说清楚。最后,答案取决于 表定义 - 在 psql 中为您提供\d product。列可以为 NULL 吗?

标签: python sql postgresql


【解决方案1】:

如果我理解正确,如果$1$2 都填写了,那么您希望它们被视为or。如果只有一个,你只想要那个。

这应该实现该逻辑:

where (color = $1 and $1 <> '') or (type = $2 and $2 <> '')

但是,如果您的表很大,我建议您尽可能将最简单的where 子句放在一起。因此,使用 python 逻辑来构造其中之一:

where color = $1
where type = $2
where color = $1 or type = $2

前两个(至少)可以利用适当的索引。

【讨论】:

    【解决方案2】:

    要么...

    select * from product where color=$1 and (type=$2 or $2='')
    

    或... 返回任何与颜色和类型匹配的东西以及没有指定类型的产品

    select * from product where color='blue' and (type='suv' or type is null)
    

    ...这取决于您想要返回什么。

    如果颜色和类型都可能传入也可能不传入,并且您想在查询中使用其中任何一个,那么:

    select * from product where (color=$1 or $1='') and (type=$2 or $2='')
    

    【讨论】:

    • 实际上我正在使用它是搜索过程,所以我可以输入“颜色”和“类型”,或者我将输入其中任何一个,然后我会相应地给出该产品
    • 你的意思是你想要这个...where (color = 'blue' or color is null) and (type = 'suv' or type is null)
    • 其实我认为你想要这个...select * from product where (color=$1 or $1='') and (type=$2 or $2='') ...从 4 个适合您的解决方案中选择。
    • 但问题是,如果我提到 color=red 值并键入空,那么它会将类型视为 null 并返回所有产品,而不仅仅是红色汽车 :(
    • where (color=$1 or $1='') and (type=$2 or $2='') 将工作。 AND 确保您仍然可以获得“红色”(或其他)汽车,无论类型如何。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 2011-02-27
    • 2011-05-11
    • 1970-01-01
    相关资源
    最近更新 更多