使用 LEFT JOIN 对 MySQL 查询进行排序
我有两个 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
查询来提取 a 冠军持有者:
SELECT c.id, h.winner
FROM championships c
LEFT JOIN title_history h
ON c.id = h.championship
ORDER BY c.rank ASC
但是,这只是在默认索引 (id< /code> 我想)。当我尝试添加
ORDER BY h.date_won
作为子句时,查询似乎失败并没有返回任何结果。
我做错了什么吗?
I have two MySQL database tables: one containing a list of championships and another recording title changes. The schemas look like this:
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
I want to be able to pull the latest title holder. I can currently pull a title holder with the following MySQL LEFT JOIN
query:
SELECT c.id, h.winner
FROM championships c
LEFT JOIN title_history h
ON c.id = h.championship
ORDER BY c.rank ASC
However, this just pulls the first result for each championship on a default index (id
I presume). When I tried added ORDER BY h.date_won
as a clause the query seems to fall over and return no results.
Am I doing something wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将仅显示最后一个(决定的)冠军:
要显示所有冠军及其获胜者,您的
LEFT JOIN
尝试似乎是正确的。也许您想按date_won
对结果进行排序:或按重要性排序(对于具有相同重要性的冠军则按 date_won 排序):
This will show just the last (decided) championship:
To show all championship and their winners, your
LEFT JOIN
attempt seems correct. Perhaps you want to order the results bydate_won
:or order by importance (and by date_won for championships with same importance):
我想我已经破解了!以下查询似乎给了我我需要的东西:
编辑:我还没有破解它。由于我按冠军 ID 进行分组,因此我现在只获得第一个冠军头衔获得者,即使之后还有冠军头衔获得者。
编辑2:通过以下查询解决:
I think I've cracked it! The following query seems to give me what I need:
EDIT: I haven't cracked it. As I'm grouping by championship ID, I'm now only getting the first title winner, even if there have been title winners after.
EDIT 2: Solved with the following query: