LEFT JOIN订单和限制

时间:2011-10-17 00:01:47

标签: mysql join left-join sql-order-by

这是我的疑问:

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`)

我的问题是这个左连接:

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

因为,如果a有很多行,它会像我的情况一样返回:

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

我希望它选择a.name order级别为desc并限制为1,因此它会返回更高level的名称(a.account_id = fr.author)

希望你能得到我。如果没有,请随时发表评论。

2 个答案:

答案 0 :(得分:33)

尝试更换:

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

使用:

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
       )

答案 1 :(得分:2)

将LEFT JOIN子句替换为:

...
LEFT JOIN (SELECT b.account_id, b.name
             FROM (SELECT c.account_id, MAX(c.level) AS level
                     FROM ps AS c
                    GROUP BY c.account_id) AS d
             JOIN ps AS b ON b.account_id = d.account_id AND b.level = d.level
          ) AS a
       ON (a.account_id = fr.author)
...

如果ps中有多个行具有相同的帐户ID且级别相同且该级别为最高级别,则仍会返回多行:

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

如果出现这种情况,那么你必须决定你想做什么 - 并适当地调整查询。例如,您可能决定将MAX(b.name)与GROUP BY子句一起使用,以便在两个名称的后面按字母顺序选择。