簡體   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