我是新来的postgresql
。我正在尝试编写一个postgresql
用于搜索的函数,该函数将仅返回匹配的 ID,并将订单 ID 作为参数中提供的列名返回。
我试图以不同的方式解决问题。
如果排序列在结果集中没有,我已经阅读了在条件情况下不排序数据的顺序。但是我编写的下面的函数,如果在 DB 中提供的列类型是text/character varying/date ,则返回ASC排序中的 ID ,我测试过。对于整数/浮点类型列,根本不排序 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$
我也尝试这种方式来订购太简单:如果类型为 text/date/integer/float
ORDERY BY _sort_field
,
ORDER BY quote_ident(_sort_field);
它不会对任何列进行 asc/desc 排序!
我正在使用 postgresql-9.5.1-1-windows-x64 版本