Postgres:无法识别未知类型的排序运算符
Postgres: Could not identify an ordering operator for type unknown
我有这个带有准备语句的查询:
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY
LIMIT
我将 name ASC
的值发送到 </code> 并将 <code>10
的值发送到 </code></p>
<p>出于某种原因,我收到此错误:</p>
<pre><code>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
它工作正常。
我做错了什么?
您不能将列名作为变量传递(除非您正在使用动态查询构建)
对于一列,您可以使用 CASE WHEN
对其进行参数化:
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY
CASE WHEN = 'name' THEN name
WHEN = 'col_name' THEN col_name
ELSE ...
END
LIMIT ;
或:
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY
CASE
WHEN 'name' THEN name
WHEN 'col_name' THEN col_name
ELSE column_name -- default sorting
END
LIMIT ;
使用 CASE
您不需要将列转换为相同的数据类型以避免隐式转换错误。
编辑:
SELECT sub.*
FROM (
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
) As sub
ORDER BY
CASE
WHEN 'name' THEN name
WHEN 'col_name' THEN col_name
ELSE column_name -- default sorting
END
LIMIT ;
我有这个带有准备语句的查询:
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY
LIMIT
我将 name ASC
的值发送到 </code> 并将 <code>10
的值发送到 </code></p>
<p>出于某种原因,我收到此错误:</p>
<pre><code>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
它工作正常。
我做错了什么?
您不能将列名作为变量传递(除非您正在使用动态查询构建)
对于一列,您可以使用 CASE WHEN
对其进行参数化:
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY
CASE WHEN = 'name' THEN name
WHEN = 'col_name' THEN col_name
ELSE ...
END
LIMIT ;
或:
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
ORDER BY
CASE
WHEN 'name' THEN name
WHEN 'col_name' THEN col_name
ELSE column_name -- default sorting
END
LIMIT ;
使用 CASE
您不需要将列转换为相同的数据类型以避免隐式转换错误。
编辑:
SELECT sub.*
FROM (
SELECT * FROM ONLY service_services
UNION ALL
SELECT * FROM fleet.service_services
WHERE deleted=false
) As sub
ORDER BY
CASE
WHEN 'name' THEN name
WHEN 'col_name' THEN col_name
ELSE column_name -- default sorting
END
LIMIT ;