简体   繁体   中英

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 . The comments table has post id pid , comment id cid and timestamp 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

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.

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.

In many databases, your query would have failed because the ordering column is not part of the group by clause... but not in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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