【问题标题】:dynamic order by sql postgresqlsql postgresql的动态排序
【发布时间】:2018-02-18 19:42:18
【问题描述】:

如何在 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;

psql 客户端返回此错误:

ERROR:  syntax error at or near "ASC"
LINE 16: ...t_column (CASE WHEN p_sort_direction = 'ASC' THEN ASC ELSE D...

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

【问题讨论】:

    标签: sql postgresql stored-procedures plpgsql


    【解决方案1】:

    使用两个不同的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);
    

    请注意,您还有另一个问题。 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,
             . . .
    

    【讨论】:

    • 谢谢 Gordon,看起来动态 SQL 对我来说可能是一个更干净的解决方案
    猜你喜欢
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 2020-11-11
    • 2019-07-15
    • 1970-01-01
    相关资源
    最近更新 更多