mysql - Unknown column from within double nested derived table in JOIN statement -


in db, there 2 types of images: challenges, , answers. both have lat/lng location columns. in query, wish select challenge or answer user created recently via inner join.

(the business logic behind this: want obtain list of users includes user's last known location, determined recent challenge or answer - whichever recent. if user not have last known location, should not included in list.)

i getting [err] 1054 - unknown column 'u.id' in 'where clause':

select     u.id,     u.totalpoints,     lastimage.lat,     lastimage.lng user u inner join (     select lat, lng     (         (select lat, lng, createdon answerimage userid = u.id order id desc limit 1)         union         (select lat, lng, createdon challengeimage userid = u.id order id desc limit 1)     ) lastimages order createdon desc limit 1 ) lastimage u.type = 1 , u.status = 2 order totalpoints desc; 

i cannot seem reference user table (alias u) within derived 'lastimages' table (or whatever proper term is).

can help? i've tried other methods, none meet requirements:

  1. a row returned if user has @ least 1 challenge or 1 answer (hence union)
  2. the recent (as determined challengeimage.createdon , answerimage.createdon) image used in join

thanks!

select u.id,        u.totalpoints,        if(ifnull(a.createdon, '1900-01-01') > ifnull(c.createdon, '1900-01-01'), a.lat, c.lat) lat,        if(ifnull(a.createdon, '1900-01-01') > ifnull(c.createdon, '1900-01-01'), a.lng, c.lng) lng user u left join     (select userid, lat, lng, createdon      answerimage      join (select userid, max(createdon) createdon            answerimage            group userid) amax      using (userid, createdon))     on u.id = a.userid left join     (select userid, lat, lng, createdon      challengeimage c      join (select userid, max(createdon) createdon            challengeimage            group userid) cmax      using (userid, createdon)) c     on u.id = c.userid u.type = 1 , u.status = 2     , (a.lat not null or c.lat not null) order totalpoints desc; 

the subqueries 1 of common ways last row per group in table, see

retrieving last record in each group

then left join them user table you'll results if user doesn't have matches in both tables.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -