如果读取发表文章最多的10个用户。。用户文章2个表 文章表里面有uid 作为表示 不存在主外建 仅仅是文字表里面有个uid 是用户的id 不知道大大能不能明白 3q sql server 2005数据库
SELECT TOP 10 uid, COUNT(*) AS Total FROM topic GROUP BY uid ORDER BY Total DESC
total 是表名么?
外层再加一个select * from users where uid in {子查询}
SELECT * FROM wj_User WHERE wj_ID IN (SELECT TOP 10 A.n_uid FROM (SELECT COUNT(*) c,n_uid FROM News WHERE n_uid!='0' GROUP BY News.n_uid ) A ORDER BY A.c DESC )
@水牛刀刀: 这个括号里面的排序是对的,但是最终结果排序是根据id 来的 如何让最终结果遵循里面的排序?
as total 是数据库字段别名,这里只是用了下group by 分组汇总。
楼主可以看下SQL的基础知识资料,
http://www.cnblogs.com/zysbk/archive/2012/09/09/langmanqishi.html
你们都是坑分的 。。我写出来了 。。贴出来吧
SELECT * FROM wj_User WHERE wj_ID IN (SELECT TOP 10 A.n_uid FROM (SELECT COUNT(*) c,n_uid FROM News WHERE n_uid!='0' GROUP BY News.n_uid ) A ORDER BY A.c DESC )
@单音节: 楼主明确了表结构,
语句优化下:
SELECT * FROM wj_User a INNER JOIN ( SELECT TOP 10 A1.n_uid, COUNT(*) AS Total FROM News A1 WHERE A1.n_uid != '0' GROUP BY A1.n_uid ORDER BY Total DESC ) b ON a.wj_ID = b.n_uid
效率应该好于in的查询,并且声调了冗余的子查询选择 前10名
SELECT TOP 10 uid, COUNT(*) AS Total FROM topic GROUP BY uid ORDER BY Total DESC