繁体   English   中英

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

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

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

post表有 post id pidtitle comments表有帖子 ID pid 、评论 ID cid和时间戳ts

table post {
   int pid 
   varchar title
}

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

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

我尝试了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;

我也试过

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;

但它没有返回任何结果。

有人可以帮忙吗

您对group by最初尝试已接近尾声。

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

在许多数据库中,您的查询会失败,因为排序列不是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 of c.ts来加快 cid 中的性能,这是注释表的主键。

暂无
暂无

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

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