sql语句 实现两个表查询显示,有一个聚合函数count()

2024-12-16 03:57:37
推荐回答(4个)
回答1:

首先这个应该是外连接查询。你知道你错在何处吗?你要查询所有的news,为什么还要限定n.newsid=@ID,你这样查询的只有一条记录了。
select top 10 n.newid,count(c.*) from new as n left jion conmment as c
on n.newid=c.newid group by n.newid order by count(c.*) desc

回答2:

这个我们首先可以对2张表按newsid进行连接,
然后按new进行分组计数即可。

select n.newId, count(c.*)
from new as n
left join comment as c on c.newId = n.newId
group by n.newId

回答3:

select top 10 n.*,d.p from new n, (select count(*) as p,newId from comment group by newId) d where n.newId=@id and n.newId = d.newId order by d.p desc

回答4:

select n.newId, count(c.*)
from new as n
left join comment as c on c.newId = n.newId
group by n.newId
order by count(c.*) desc

应该没问题的。