是否有一种方法可以从DB2中的where子句中的条件集获取结果?



我有一般的衬衫库存表:尺寸,颜色和品牌。我必须找到匹配的价格,并把它们添加到电子表格的列表中

我对[大号,红色,耐克],[小号,白色,彪马]和[中号,蓝色,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条件任意组合的长清单。然后,我将执行x查找以找到我需要的三个确切的组合。

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

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

是否有办法创建一个简单的循环来循环,比如说,一个条件数组?就像

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数据库,如果这有区别的话…

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

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')

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

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


[大号,红色,Nike]获得组号1
[小号,白色,Puma]获得组号2
[中号,蓝色,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;

最新更新