简体   繁体   English

使用mysql中另一个表中的值对选择结果进行排序

[英]sorting select results using values from another table in mysql

I have two tables, posts and comments.我有两个表,帖子和评论。 Each post has at least one comment.每个帖子至少有一条评论。 My tables look like following我的表格如下所示

The post table has post id pid and a title . post表有 post id pidtitle The comments table has post id pid , comment id cid and timestamp ts comments表有帖子 ID pid 、评论 ID cid和时间戳ts

table post {
   int pid 
   varchar title
}

table comments {
   int pid
   int cid 
   int ts
   varchar comment
}

I like to list all the posts sorted by showing the post with the latest comment on the top.我喜欢通过在顶部显示最新评论的帖子来列出所有帖子。

I tried group by but it did not work as expected我尝试了group by但它没有按预期工作

select p.pid, c.ts from posts p, comments c where c.pid=p.pid group by p.pid order by c.ts desc;

I also tried我也试过

select p.pid, c.ts from posts p join (select pid, max(ts) from comments) c on c.pid=p.pid order by c.ts desc;

but it did not return any results.但它没有返回任何结果。

Can someone help有人可以帮忙吗

Your original attempt with group by was close.您对group by最初尝试已接近尾声。

The thing is that you need to order by the maximum timestamp of the group, which implies using an aggregate function in the group by clause.问题是您需要按组的最大时间戳排序,这意味着在group by子句中使用聚合函数。

In many databases, your query would have failed because the ordering column is not part of the group by clause... but not in MySQL.在许多数据库中,您的查询会失败,因为排序列不是group by子句的一部分……但在 MySQL 中不是。

select p.pid, max(c.ts) last_ts
from posts p
inner join comments c on c.pid=p.pid 
group by p.pid 
order by max(c.ts) desc;

Note: always use explicit, standard joins rather than old-school, implicit joins.注意:始终使用显式的标准连接,而不是老式的隐式连接。

select p.pid, max(c.ts) as latest_comment
from posts p
left join comments c on c.pid=p.pid 
group by p.pid 
order by latest_comment desc;

You can also use c.cid intead of c.ts to speed up performance in cid is primary key for comments table.您还可以使用c.cid of c.ts来加快 cid 中的性能,这是注释表的主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM