2017-03-15 46 views
1

我有一个REST端点是这样的:选择列名其中列名= all_values

www.icecreamstore.com/stock?brand=hershey&flavour=vanilla

现在,

两个brandflavour是可选的。

所以下面也是完全有效的:

www.icecreamstore.com/stock?flavour=vanilla

www.icecreamstore.com/stock?brand=hershey

www.icecreamstore.com/stock

这些API映射到SQL查询:

select count(*) from stock where brand=? and flavour=?

是否可以使用单个查询,而不是为每个请求参数组合编写单独的查询。

另外,

是否有可能写出这样的查询:

select count(*) from stock where brand=* and flavour=*

注:我与LIKE在没有请求参数的情况下,使用column_name LIKE '%%'目前管理。但是,如果列不存储字符串类型的值。

+0

您正在使用哪些DBMS? Postgres的?甲骨文? –

+0

我正在使用postgres –

回答

2

对于你的特殊情况,最简单的方法可能是:

select count(*) 
from stock 
where brand = coalesce(?, brand) and flavour = coalesce(?, flavour); 

这假定brandflavour从来NULL

如果他们可以NULL,您可以使用is not distinct from

select count(*) 
from stock 
where brand is not distinct from coalesce(?, brand) and 
     flavour is not distinct from coalesce(?, flavour); 
0

要获得所有值,您还可以在查询中写一个静态值绕过第一条件是不正确的:

select count(*) 
from stock 
where (brand=<to get single> or 'allBrand'='allBrand') AND 
(flavour=<to get single> or 'allFlavour'='allFlavour')