gpt4 book ai didi

sql - Postgres : Could not identify an ordering operator for type unknown

转载 作者:行者123 更新时间:2023-11-29 12:59:43 30 4
gpt4 key购买 nike

我有这个带有准备语句的查询:

SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY $1
LIMIT $2

我将 name ASC 的值发送到 $1 并将 10 的值发送到 $2

出于某种原因,我收到此错误:

could not identify an ordering operator for type unknown

如果我硬编码 name ASC 而不是 $1,像这样:

SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY name ASC
LIMIT $1

它工作正常。

我做错了什么?

最佳答案

对于一列,您可以使用 CASE WHEN 对其进行参数化:

SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY
CASE WHEN $1 = 'name' THEN name
WHEN $1 = 'col_name' THEN col_name
ELSE ...
END
LIMIT $2;

或:

SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY
CASE $1
WHEN 'name' THEN name
WHEN 'col_name' THEN col_name
ELSE column_name -- default sorting
END
LIMIT $2;

使用 CASE,您不需要将列转换为相同的数据类型以避免隐式转换错误。

编辑:

SELECT sub.*
FROM (
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
) As sub
ORDER BY
CASE $1
WHEN 'name' THEN name
WHEN 'col_name' THEN col_name
ELSE column_name -- default sorting
END
LIMIT $2;

关于sql - Postgres : Could not identify an ordering operator for type unknown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802385/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com