我有这个查询准备好的声明:
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
工作正常。
我做错了什么?
答案 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;