LEFT JOIN order and limit

Cyclone picture Cyclone · Oct 17, 2011 · Viewed 35.4k times · Source

This is my query:

SELECT `p`.`name` AS 'postauthor', `a`.`name` AS 'authorname',
       `fr`.`pid`, `fp`.`post_topic` AS 'threadname', `fr`.`reason`
  FROM `z_forum_reports` `fr`
  LEFT JOIN `forums` `f` ON (`f`.`id` = `fr`.`pid`)
  LEFT JOIN `forums` `fp` ON (`f`.`first_post` = `fp`.`id`) 
  LEFT JOIN `ps` `p` ON (`p`.`id` = `f`.`author_guid`)
  LEFT JOIN `ps` `a` ON (`a`.`account_id` = `fr`.`author`)

My problem is this left join:

SELECT `a`.`name`, `a`.`level`
[..]
LEFT JOIN `ps` `a` ON (`a`.`account_id` = `fr`.`author`)

Since, in case a has MANY rows and it'll return like in my case:

NAME  | LEVEL
Test1 | 1
Test2 | 120
Test3 | 2
Test4 | 1 

I want it to select a.name with order of level desc and limit 1, so it'll return the name of higher level where (a.account_id = fr.author).

Hope you got me. If not, feel free to post a comment.

Answer

ypercubeᵀᴹ picture ypercubeᵀᴹ · Oct 17, 2011

Try replacing:

LEFT JOIN ps a ON a.account_id = fr.author

with:

LEFT JOIN ps a 
  ON a.PrimaryKey                         --- the Primary Key of ps
     = ( SELECT b.PrimaryKey 
         FROM ps AS b 
         WHERE b.account_id = fr.author
         ORDER BY b.level DESC
         LIMIT 1
       )