两个表关联查询,max与groupby的联合使用

假设有两个表。文章表和评论表。如下:
article (
id int not null,
title varchar not null,
content varchar,
primary key(id)
);

comment (
id int not null,
article_id int not null,
content varchar,
addtime date,
primary key(id)
);


1. 一篇文章有多条评论,需求要求知道所有文章的最后一条评论内容

首先列举下我开始使用的错误命令:
select a.title, c.content, max(c.addtime) from article a, comment c 
where a.id = c.c.article_id group by(a.id) ;


根据article_id关联起来两个表,主表article,副表comment。
where后的等式查询后结果会是一个文章对应多个评论,然后通过max函数和group by得到每个文章里面评论时间最靠后的时间点。
经过这个查询,得到的addtime,title是正确的,但是content将是随机的。


正确的语句如下:
select tmp.title, c.content from 
(select a.id article_id, a.title title, max(c.addtime) addtime
from article a, comment c 
where a.id = c.article_id group by(a.id) order by null) tmp
inner join content con on con.article_id = tmp.article_id and com.addtime = tmp.addtime;

因为group by默认会进行排序,使用order by null可以减少开销。

猜你喜欢

转载自981747983-qq-com.iteye.com/blog/1597866
今日推荐