昨天无意识看到同桌的同事在练习sql,其中看到他在写一道题的sql,
求出发帖最多的人?
开始我写的是这句:
select t.authorid,max(total) from (select authorid,count(*) total from articles
group by authorid ) t group by t.authorid 结果去执行,完了,错的! 写了两句相当于
写了一句,都是一样的结果。
正确的写法如下:
select teaid,count(*) total from articles group by teaid having count(*) =
(select max(total2) from (select count(*) total2 from articles group by teaid) t);
记得不能写成如下这样哦:
select teaid,count(*) total from articles group by teaid
having total = //total 一定要写成 count(*)
(select max(total2) from (select count(*) total2 from articles group by teaid) t);
下面这样写直接报错
select teaid,count(*) total from articles group by teaid having
count(*)=max(total)
也不应该写成:
select teaid,count(*) total from articles group by teaid
having total = //total 一定要写成 count(*)
(select max(total2) from (select count(*) total2 from articles group by teaid)
as t);//子查询不能加as as只能用作表的别名
下面的写法也会报错
select teaid , count(*) c from articles group by teaid
having count(*) = select max(t.total) from (select teaid,count(*) total from articles group by teaid) t
应该写成下面这样
select teaid , count(*) c from articles group by teaid
having count(*) = (select max(t.total) from (select teaid,count(*) total from
articles group by teaid) t)//应该加上括号
求出发帖最多的人?
开始我写的是这句:
select t.authorid,max(total) from (select authorid,count(*) total from articles
group by authorid ) t group by t.authorid 结果去执行,完了,错的! 写了两句相当于
写了一句,都是一样的结果。
正确的写法如下:
select teaid,count(*) total from articles group by teaid having count(*) =
(select max(total2) from (select count(*) total2 from articles group by teaid) t);
记得不能写成如下这样哦:
select teaid,count(*) total from articles group by teaid
having total = //total 一定要写成 count(*)
(select max(total2) from (select count(*) total2 from articles group by teaid) t);
下面这样写直接报错
select teaid,count(*) total from articles group by teaid having
count(*)=max(total)
也不应该写成:
select teaid,count(*) total from articles group by teaid
having total = //total 一定要写成 count(*)
(select max(total2) from (select count(*) total2 from articles group by teaid)
as t);//子查询不能加as as只能用作表的别名
下面的写法也会报错
select teaid , count(*) c from articles group by teaid
having count(*) = select max(t.total) from (select teaid,count(*) total from articles group by teaid) t
应该写成下面这样
select teaid , count(*) c from articles group by teaid
having count(*) = (select max(t.total) from (select teaid,count(*) total from
articles group by teaid) t)//应该加上括号
本文纠正了一种常见的SQL查询错误,即如何正确地找出在文章表中发帖数量最多的作者。通过对比不同写法,解释了为何某些SQL语句无法得出预期结果,并给出了正确的实现方法。
1万+

被折叠的 条评论
为什么被折叠?



