Postgres:无法识别类型未知的排序运算符

时间:2015-11-19 11:16:15

标签: sql postgresql prepared-statement

我有这个查询准备好的声明:

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

我将name ASC的值发送到$110发送到$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

工作正常。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您不能将列名称作为变量传递(除非您使用动态查询构建)

答案 1 :(得分: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;