【问题标题】:Is there a way to get result from sets of conditions in where clauses in DB2有没有办法从 DB2 中 where 子句中的条件集获取结果
【发布时间】:2021-03-11 19:58:45
【问题描述】:

我有常用的衬衫库存表:尺码、颜色和品牌。我必须找到匹配的价格并添加到电子表格中的列表中

我对[大号、红色、耐克]、[小号、白色、彪马]和[中号、蓝色、H&M]感兴趣

我现在正在做的是:

select size,colour,brand,price from inventory 
where size in ('large','small','medium')
and colour in ('red','white','blue')
and brand in ('Nike','Puma','H&M')

然后我得到一长串满足 3*3 条件的任意组合的库存。然后我会做一个 xlookup 来找到我需要的三个确切的组合。

(我的实际列表显然要长得多,并且包含更多具有更多值的变量。但这是最简单的示例)

这显然非常无效,但我不知道如何使我的查询更直接。

是否有某种方法可以创建一个简单的循环,例如循环一个条件数组?类似的东西

condA=('large','small','medium')
condB= ('red','white','blue')
condC=('Nike','Puma','H&M')
for a = 0 to 2
select size, colour,brand,price from inventory 
where size=condA(a)
and colour=condB(a)
and brand=condC(a)
next a

我正在使用 DB2 数据库,如果这会有所不同...

【问题讨论】:

  • 哪里(尺寸、颜色、品牌)IN (('large', 'red', 'Nike'), ...)?

标签: sql db2 where-clause


【解决方案1】:

最好的方法是使用您正在寻找的确切组合直接过滤案例:

select size,colour,brand,price from inventory 
where (size ='large' and brand = 'Nike' and colour='red')
or ( size ='small' and brand = 'Puma' and colour='white') 
or (size ='medium' and brand = 'H&M' and colour='blue')

这样您就不需要查看提取的结果来确保组合正确

【讨论】:

    【解决方案2】:

    只需为每个属性分配一个“组号”,并在WHERE 子句中使用这样的组号。优点是,您不必指定一长串 OR'ed 谓词。如果您愿意,只需为每种属性类型创建 3 个表引用就足够了。

    在下面的组合示例中:
    [大、红、耐克] 获得组号 1
    [小、白、彪马] 获得组号 2
    [medium, blue, H&M] 获得组号 3

    select 
      inventory.size
    , inventory.colour
    , inventory.brand
    , inventory.price 
    from 
    (
    values 
      ('large', 'red', 'Nike', 1)
    , ('small', 'white', 'Puma', 1)
    , ('medium', 'blue', 'H&M', 1)
    -- any other combinations like below are not returned
    , ('large', 'red', 'Puma', 1)
    , ('small', 'white', 'Nike', 1)
    ) inventory (size, colour, brand, price)
    join
    (
    values ('large', 1), ('small', 2), ('medium', 3)
    ) sizes (size, id) on sizes.size = inventory.size
    join
    (
    values ('red', 1), ('white', 2), ('blue', 3)
    ) colours (colour, id) on colours.colour = inventory.colour
    join
    (
    values ('Nike', 1), ('Puma', 2), ('H&M', 3)
    ) brands (brand, id) on brands.brand = inventory.brand
    where sizes.id = colours.id and colours.id = brands.id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      相关资源
      最近更新 更多