LEFT JOIN秩序和限制

问题描述 投票:14回答:2

这是我的查询:

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和限制1 order选择desc,所以它会返回更高level其中(a.account_id = fr.author)的名称。

希望你有我。如果没有,随意发表评论。

mysql join left-join sql-order-by
2个回答
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
       )

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) BY子句中任意选择字母后面的两个名字。

© www.soinside.com 2019 - 2024. All rights reserved.