views:

530

answers:

3

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 that I can't quite understand the problem with:

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

...query:

   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

clause "l.user_id as l_user_id, l.geopoint_id as l_geopoint_id" was added because apparently postgres doesn't like order clauses with fields not selected. But the error I now get makes it look like I'm also not getting aliasing. Anybody with postgres experience see the problem?

I'm likely to have a bunch of these problems -- the queries worked fine in mySql...

+3  A: 

You have:

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

in your query. That's illegal syntax. Remove the = l2.user_id part (move it to where if that's one of the join conditions) and it should work.

Update Below select (with = l2.user_id removed) should work just fine. I've tested it (with different table / column names, obviously) on 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
ChssPly76
I changed the references to non-aliased ones, and all is fine. Changes to what you suggest did not change the alias problem, though: it still does not like the l_user_id alias...
Dan Donaldson
Take a look at my update above - that query works just fine.
ChssPly76
This is not equivalent of the query in question. "order by l_user_id = l2.user_id desc" means that rows where l.user_id and l2.user_id are equal have to go first.
Tometzky
A: 

"was added because apparently postgres doesn't like order clauses with fields not selected"

"As far as order by goes - yes, PostgresQL (and many other databases) does not allow ordering by columns that are not listed in select clause."

Just plain untrue.

=> SELECT id FROM t1 ORDER BY owner LIMIT 5;

id

30 10 20 50 40 (5 rows)

Richard Huxton
You're right, this is supported since 8.0
ChssPly76
A: 
Tometzky
OK -- that makes sense, in light of the rule, but not entirely intuitive to someone who has been using mySql for years. I'll try it in code...
Dan Donaldson