【发布时间】:2017-07-15 10:12:13
【问题描述】:
我是postgresql 的新手。我正在尝试编写一个用于搜索的postgresql 函数,该函数将仅返回匹配的 ID,并将订单 ID 作为参数中提供的列名返回。
我尝试以不同的方式解决问题。
如果排序列在结果集中没有,我已经阅读了在条件情况下不排序数据的顺序。但是我编写的下面的函数,如果在 DB 中提供的列类型是 文本/字符变化/日期,则返回 ASC 中的 ID,我测试过。对于 integer/float 类型的列根本不排序 ID。现在,我需要根据需要对整数/浮点类型列以及 ASC/DESC 进行排序。
CREATE OR REPLACE FUNCTION public.search_products(_name text DEFAULT NULL::text, _category_id integer DEFAULT NULL::integer, _min_mrp double precision DEFAULT NULL::double precision, _max_mrp double precision DEFAULT NULL::double precision, _sort_field text DEFAULT NULL::text)
RETURNS SETOF bigint
LANGUAGE sql
AS $function$
select product.id
from product
where
case
when _category_id is null then (_name is null or lower(product.name) like '%'|| lower(_name) ||'%' and (_min_mrp is null or _max_mrp is null Or (product.market_retail_price BETWEEN _min_mrp and _max_mrp)))
when _category_id is not null then (_name is null or lower(product.name) like '%'|| lower(_name) ||'%' and (_min_mrp is null or _max_mrp is null Or (product.market_retail_price BETWEEN _min_mrp and _max_mrp))) /*will be updated after category id deciding */
end
ORDER BY
CASE
WHEN(_sort_field similar to 'market_retail_price asc') THEN product.market_retail_price || ' ASC' /* it is float type column, and not working for asc/desc anything */
WHEN(_sort_field similar to 'approved_by asc') THEN product.approved_by || ' ASC' /* it is integer type column, and not working for asc/desc anything */
WHEN(_sort_field similar to 'approved_on asc') THEN product.approved_on || ' ASC' /* date type column, it works for asc order only. Even if text is 'approved_on desc' in other case, it match the case, but returns data in asc order only. THAT'S TOTALLY WIERED. Never sort desc. */
WHEN(_sort_field similar to 'supplier_id asc') THEN product.supplier_id || ' ASC'
WHEN(_sort_field similar to 'product_status asc') THEN product.product_status || ' ASC' /* text type, and working for asc only */
WHEN(_sort_field similar to 'name desc') THEN (product.name || ' DESC') /* not working for desc order, but returns data in asc sort */
ELSE product.id || ' ASC'
END
$function$
我也尝试这种方式订购太简单了:ORDERY BY _sort_field
和 ORDER BY quote_ident(_sort_field);
如果类型为 text/date/integer/float,它不会对任何列进行 asc/desc 排序!
我使用的是 postgresql-9.5.1-1-windows-x64 版本
【问题讨论】:
-
你必须使用dynamic SQL 来做类似的事情。小心 SQL 注入!
标签: database postgresql sql-parametrized-query sql-order-by