sql postgresql 动态排序

Dan*_*Dan 3 sql postgresql stored-procedures plpgsql

我如何在 postgresql 函数中实现按列和排序方向的动态排序。

这是我到目前为止所拥有的:

CREATE OR REPLACE FUNCTION get_urls_by_crawl_id(
    p_account_id character varying(64),
    p_crawl_id character varying(64),
    p_sort_column character varying(30),
    p_sort_direction character varying(30),
    p_page integer,
    p_total integer
)
RETURNS TABLE(id character varying(64), source_url text, http_status_code integer, ref_cnt integer) AS $BODY$
BEGIN
    RETURN QUERY SELECT u.id, u.source_url, u.http_status_code, u.ref_cnt FROM url AS u 
    JOIN crawl AS c ON(u.crawl_id = c.id) 
    JOIN site AS s ON(c.site_id = s.id)
    JOIN person AS p ON(s.person_id = p.id)
    WHERE p.account_id = p_account_id AND u.crawl_id = p_crawl_id AND u.secured = 0 
    ORDER BY p_sort_column (CASE WHEN p_sort_direction = 'ASC' THEN ASC ELSE DESC END) LIMIT p_total OFFSET (p_page * p_total);
END;
$BODY$ LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)

psql 客户端返回此错误:

ERROR:  syntax error at or near "ASC"
LINE 16: ...t_column (CASE WHEN p_sort_direction = 'ASC' THEN ASC ELSE D...
Run Code Online (Sandbox Code Playgroud)

我尝试了多种形式的 CASE 语句,但似乎都不起作用。

Gor*_*off 13

使用两个不同的order by键:

ORDER BY (case when p_sort_direction = 'ASC' then p_sort_column end)
 asc,
            p_sort_column desc
LIMIT p_total OFFSET (p_page * p_total);
Run Code Online (Sandbox Code Playgroud)

请注意,您还有另一个问题。 p_sort_column是一个字符串。您需要使用动态 SQL 将其插入代码中。

或者,您可以使用一系列cases:

order by (case when p_sort_column = 'column1' and p_sort_direction = 'ASC' then column1 end) asc,
         (case when p_sort_column = 'column1' and p_sort_direction = 'DESC' then column1 end) desc,
         (case when p_sort_column = 'column2' and p_sort_direction = 'ASC' then column2 end) asc,
         (case when p_sort_column = 'column2' and p_sort_direction = 'DESC' then column2 end) desc,
         . . .
Run Code Online (Sandbox Code Playgroud)