[英]select column_name from table where column_name = all_values
我有这样的REST端点:
www.icecreamstore.com/stock?brand=hershey&flavour=vanilla
现在,
brand
和flavour
都是可选的。
因此以下内容也完全有效:
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=*
注意:如果没有请求参数,我目前正在使用column_name LIKE '%%'
来管理LIKE
。 但是,如果列不存储字符串类型的值,该怎么办。
对于您的特定情况,最简单的方法可能是:
select count(*)
from stock
where brand = coalesce(?, brand) and flavour = coalesce(?, flavour);
这假设brand
和flavour
永远不会为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);
要获取所有值,您还可以在查询中写一个静态值以在第一个条件不成立的情况下跳过:
select count(*)
from stock
where (brand=<to get single> or 'allBrand'='allBrand') AND
(flavour=<to get single> or 'allFlavour'='allFlavour')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.