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

使用mysql中另一个表的值对select结果进行排序,mysql,Mysql,我有两个表格,帖子和评论。每个帖子至少有一条评论。我的桌子如下所示 post表具有post idpid和标题。comments表具有post idpid、comment idcid和timestampts table post { int pid varchar title } table comments { int pid int cid int ts varchar comment } 我喜欢列出所有的帖子,通过在顶部显示最新评论的帖子来排序

我有两个表格,帖子和评论。每个帖子至少有一条评论。我的桌子如下所示

post
表具有post id
pid
标题
comments
表具有post id
pid
、comment id
cid
和timestamp
ts

table post {
   int pid 
   varchar title
}

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

我喜欢列出所有的帖子,通过在顶部显示最新评论的帖子来排序

我尝试了
groupby
,但没有达到预期效果

select p.pid, c.ts from posts p, comments c where c.pid=p.pid group by p.pid order by c.ts desc;
我也试过了

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;
但它没有返回任何结果


有人能帮忙吗

您最初尝试的
分组方式已接近成功

问题是您需要按组的最大时间戳排序,这意味着在
groupby
子句中使用聚合函数

在许多数据库中,查询都会失败,因为排序列不是
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;
注意:始终使用显式的标准联接,而不是老式的隐式联接

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;

您还可以使用
c.cid
intead of
c.ts
来加快性能,因为cid是comments表的主键。

您可以发布SHOW CREATE table comments的文本结果吗;请同时发布显示创建表格帖子的文本结果;请张贴2个显示创建表xx;几天前被要求。谢谢,当帖子数量超过10万条时,对max(c.ts)的绩效处罚有何评论