Dan*_*son 11 mysql sql postgresql alias heroku
作为Postgresql的新手(我正在移动,因为我正在将我的网站移动到只支持它的heroku,我不得不重构我的一些查询和代码.这是一个我无法理解这个问题的问题有:
PGError: ERROR: column "l_user_id" does not exist
LINE 1: ...t_id where l.user_id = 8 order by l2.geopoint_id, l_user_id ...
^
Run Code Online (Sandbox Code Playgroud)
...查询:
select distinct
l2.*,
l.user_id as l_user_id,
l.geopoint_id as l_geopoint_id
from locations l
left join locations l2 on l.geopoint_id = l2.geopoint_id
where l.user_id = 8
order by l2.geopoint_id, l_user_id = l2.user_id desc
Run Code Online (Sandbox Code Playgroud)
添加了"l.user_id为l_user_id,l.geopoint_id为l_geopoint_id"的子句,因为显然postgres不喜欢未选中字段的order子句.但是我现在得到的错误使它看起来像我也没有得到别名.任何有postgres经验的人都会看到问题吗?
我可能会遇到一堆这样的问题 - 查询在mySql中运行良好...
Tom*_*zky 16
在PostgreSQL中,您不能按顺序使用带别名的表达式.只有普通的别名在那里工作.您的查询应如下所示:
select distinct
l2.*,
l.user_id as l_user_id,
l.geopoint_id as l_geopoint_id
from locations l
left join locations l2 on l.geopoint_id = l2.geopoint_id
where l.user_id = 8
order by l2.geopoint_id, l.user_id = l2.user_id desc;
Run Code Online (Sandbox Code Playgroud)
我猜你的意思是l2.user_id=l.user_id
应该先行.
这是 PostgreSQL通用邮件列表中的相关消息.以下是在子句的文档中ORDER BY
:
每个表达式可以是输出列的名称或序号(SELECT列表项),也可以是由输入列值组成的任意表达式.
所以在使用表达式时没有别名.
我使用fuzzystrmatch 中的函数遇到了同样的问题——尤其是levenshtein 函数。我需要按字符串距离排序,并按字符串距离过滤结果。我最初是在尝试:
SELECT thing.*,
levenshtein(thing.name, '%s') AS dist
FROM thing
WHERE dist < character_length(thing.name)/2
ORDER BY dist
Run Code Online (Sandbox Code Playgroud)
但是,当然,我从 WHERE 子句中得到了错误“列”dist“不存在”。我试过了,它奏效了:
SELECT thing.*,
(levenshtein(thing.name, '%s')) AS dist
FROM thing
ORDER BY dist
Run Code Online (Sandbox Code Playgroud)
但是我需要在 WHERE 子句中具有该限定条件。这个问题中的其他人说 WHERE 子句是在 ORDER BY 之前评估的,因此在评估 WHERE 子句时该列不存在。根据这个建议,我发现嵌套的 SELECT 语句可以解决问题:
SELECT * FROM
(SELECT thing.*,
(levenshtein(thing.name, '%s')) AS dist
FROM thing
ORDER BY dist
) items
WHERE dist < (character_length(items.name)/2)
Run Code Online (Sandbox Code Playgroud)
请注意,“items”表别名是必需的,并且可以在外部 SELECT 中访问 dist 列别名,因为它在语句中是唯一的。这有点时髦,我很惊讶它在 PG 中必须如此 - 但它似乎并没有影响性能,所以我很满意。