postgres column alias problem

后端 未结 4 739
余生分开走
余生分开走 2020-12-06 11:29

As a newbie to Postgresql (I\'m moving over because I\'m moving my site to heroku who only support it, I\'m having to refactor some of my queries and code. Here\'s a problem

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 11:34

    I ran into this same problem using functions from fuzzystrmatch - particularly the levenshtein function. I needed to both sort by the string distance, and filter results by the string distance. I was originally trying:

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

    But, of course, I got the error "column"dist" does not exist" from the WHERE clause. I tried this and it worked:

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

    But I needed to have that qualification in the WHERE clause. Someone else in this question said that the WHERE clause is evaluated before ORDER BY, thus the column was non-existent when it evaluated the WHERE clause. Going by that advice, I figured out that a nested SELECT statement does the trick:

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

    Note that the "items" table alias is required and the dist column alias is accessible in the outer SELECT because it's unique in the statement. It's a little bit funky and I'm surprised that it has to be this way in PG - but it doesn't seem to take a performance hit so I'm satisfied.

提交回复
热议问题