两个表关联查询,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可以减少开销。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值