作为 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 ...
                                                             ^

...询问:

   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

添加子句“l.user_id as l_user_id, l.geopoint_id as l_geopoint_id”是因为显然 postgres 不喜欢未选择字段的 order 子句。但我现在得到的错误使得我看起来也没有出现别名。有 postgres 经验的人看到这个问题了吗?

我可能会遇到很多这样的问题——查询在 mySql 中运行良好......

有帮助吗?

解决方案

在的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;

我假定你的意思是l2.user_id=l.user_id应该先走。

这是相关的消息的PostgreSQL 的-general邮件列表上。以下是ORDER BY条款的文档中:

  

每个表达式可以是名称或   一个的输出的序数   柱 的(选择列表项),或者它   可以是任意表达形成   从的输入列

因此,当使用表达无别名。

其他提示

您有:

order by l2.geopoint_id, l_user_id = l2.user_id desc

在您的查询。这是非法的语法。卸下= l2.user_id部(将其移动到where如果这是的连接条件之一),它应该工作。

<强>更新下面选择(与= l2.user_id移除)应该工作得很好。我上的Postgres测试了它(具有不同的表/列名,很明显)8.3

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 desc

我使用 fuzzystrmatch 中的函数遇到了同样的问题 - 特别是 levenshtein 函数。我需要按字符串距离排序,并按字符串距离过滤结果。我最初尝试的是:

SELECT thing.*, 
levenshtein(thing.name, '%s') AS dist 
FROM thing 
WHERE dist < character_length(thing.name)/2 
ORDER BY dist

但是,当然,我从 WHERE 子句中收到错误“column”dist” does not exit”。我尝试了这个并且它有效:

SELECT thing.*, 
(levenshtein(thing.name, '%s')) AS dist 
FROM thing 
ORDER BY dist

但我需要在 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)

请注意,“items”表别名是必需的,并且 dist 列别名可以在外部 SELECT 中访问,因为它在语句中是唯一的。这有点奇怪,我很惊讶在 PG 中竟然如此 - 但它似乎并没有影响性能,所以我很满意。

“的溶液中加入,因为显然Postgres没有想用未选择的字段顺序条款”

“至于为了通过去 - 是时,PostgreSQL(和许多其他数据库)不允许由未在选择子句列出的列排序”

仅有纯不真实的。

=> SELECT ID FROM T1 ORDER BY所有者LIMIT 5;

ID

30  10  20  50  40 (5行)

scroll top