使用LEFT JOIN排序MySQL查询

时间:2011-06-09 15:20:18

标签: mysql sql left-join

我有两个MySQL数据库表:一个包含锦标赛列表和另一个录音标题更改。模式如下所示:

championships

id INT AUTO_INCREMENT PRIMARY_KEY
name VARCHAR(255) NOT NULL UNIQUE
rank INT(2) NOT NULL DEFAULT '1'

title_history

id INT AUTO_INCREMENT PRIMARY_KEY
championship INT FOREIGN_KEY REFERENCES (championships.id)
winner VARCHAR(255) NOT NULL
date_won DATE NOT NULL

我希望能够拉出最新的冠军头衔。我现在可以使用以下MySQL LEFT JOIN查询来 标题持有者:

SELECT c.id, h.winner
FROM championships c
LEFT JOIN title_history h
ON c.id = h.championship
ORDER BY c.rank ASC

然而,这只是在默认指数(id我假设)上为每个冠军拉出第一个结果。当我尝试添加ORDER BY h.date_won作为子句时,查询似乎没有结果并且没有返回任何结果。

我做错了吗?

2 个答案:

答案 0 :(得分:0)

这将显示最后(决定)的冠军:

SELECT winner
FROM title_history
ORDER BY date_won DESC
LIMIT 1

要显示所有冠军及其获胜者,您的LEFT JOIN尝试似乎是正确的。也许您想按date_won订购结果:

SELECT c.id, h.winner
FROM championships c
  LEFT JOIN title_history h
    ON c.id = h.championship
ORDER BY date_won DESC

或按重要性排序(以及date_won对于具有相同重要性的锦标赛):

SELECT c.id, h.winner
FROM championships c
  LEFT JOIN title_history h
    ON c.id = h.championship
ORDER BY c.rank ASC
       , h.date_won DESC

答案 1 :(得分:0)

我想我已经破解了!以下查询似乎给了我我需要的东西:

SELECT c.id, c.name, h.winner
FROM championships c
LEFT JOIN title_history h
ON c.id = h.championship
GROUP BY c.id
ORDER BY c.rank ASC, h.date_from ASC

编辑:我没有破解它。由于我按冠军ID分组,我现在只获得第一个冠军头衔,即使之后有冠军头衔。

编辑2 :使用以下查询解决:

SELECT friendly_name,
(SELECT winner FROM title_history WHERE championship = c.id ORDER BY date_from DESC LIMIT 1) 
FROM championships AS c
ORDER BY name