在 MySQL 中加入 Select Distinct 按连接表重新排序
我四处寻找这个问题的答案,但没有找到。我有一个网站,文章存储在文章表中,作者存储在用户表中。我想要获取按作者最近写文章的时间排序的作者列表。
这给了我用户 ID:
SELECT distinct a.user_id
FROM `article` as a
ORDER BY a.id desc
问题是,一旦我尝试通过加入顺序更改来引入名称,以便它是按用户 ID 的。我已经尝试过:
SELECT distinct a.user_id, u.name
FROM `article` as a
LEFT JOIN user as u on u.id = a.user_id
ORDER BY a.id desc, u.id desc
并且
SELECT distinct a.user_id, u.name
FROM `article` as a
LEFT JOIN user as u on u.id = a.user_id
ORDER BY u.id desc, a.id desc
都改变了名称的顺序。我显然在做一些愚蠢的事情,但是什么?
I've looked around for an answer to this but I'm not finding it. I have a site with articles stored in an article table and writers in the user table. I wanted to get a list of authors ordered by how recently they'd written an article.
This gives me the User ids:
SELECT distinct a.user_id
FROM `article` as a
ORDER BY a.id desc
The problem is that as soon as I try to bring the names in by joining the order changes so that it's by user id. I've tried this:
SELECT distinct a.user_id, u.name
FROM `article` as a
LEFT JOIN user as u on u.id = a.user_id
ORDER BY a.id desc, u.id desc
and
SELECT distinct a.user_id, u.name
FROM `article` as a
LEFT JOIN user as u on u.id = a.user_id
ORDER BY u.id desc, a.id desc
but both alter the order of the names. I'm obviously doing something stupid, but what?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
事实上,在第一个示例中,DISTINCT 恰好与 ORDER BY 一起使用是侥幸,而不是标准 SQL。你需要这样的东西:
The fact that DISTINCT happens to work with ORDER BY in your first example is a fluke, and not standard SQL. You need something like this:
试试这个
try this
ORDER BY 按用户 ID 和/或文章 ID(取决于示例)对行进行排序。
如果您希望按名称进行可靠排序,请在 ORDER BY 字段中包含 u.name 字段。
Your ORDER BY sorts the rows by either the User ID and/or Article ID (depending on the example).
If you want reliable sorting by name, then include the u.name field in the ORDER BY fields.
这是postgres语法,但是你可以轻松地将其翻译成mysql
this is postgres syntax, but you can easily translate it into mysql
遵循以下内容的内容应该有效:
不确定您的字段的确切名称是什么,但这应该为您指明正确的方向。
您有很多答案可供选择...我相信您所问问题的关键是使用聚合函数 MAX() http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_max
Something along the lines of the following should work:
Not sure what exactly your fields are named and all, but this should point you in the right direction.
You got a lot of answers to choose from... I believe the key to what you're asking is use of the aggregate function MAX() http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_max