如何加入三个表并按人数评论排序?

时间:2012-10-26 07:23:27

标签: sql-server

我试图根据收到的大多数评论从三个表中获取数据,下面是我的表结构:

Table A
ID | Follower | Comment | PLACE
-------------------------------
1  | ABC      | TEXT1   | LA
3  | ABC      | TEXT1   | NY
1  | ABC      | TEXT2   | LA
2  | ABC      | TEXT1   | IL
1  | ABC      | TEXT2   | LA

Table B
ID | NAME     | PLACE
-----------------------
1  | Name1    | LA
2  | Name2    | IL
3  | Name3    | NY

Table C
PLACE | COUNTRY 
-----------------------
LA    | US      
IL    | US      
NY    | US  

我想做的是这样的事情:

    SELECT        
a.PLACE, a.ID, a.NAME, b.PLACE, Count(b.ID) AS CT, c.PLACE, c.COUNTRY
FROM            
TableB AS a INNER JOIN
TableA AS b ON a.ID = b.ID INNER JOIN
TableC AS c ON b.PLACE = c.PLACE
GROUP by b.ID
ORDER BY (CT) DESC

1 个答案:

答案 0 :(得分:0)

select b.ID,b.Name,b.Place,c.COUNTRY,a.MostComments  
from TableB b inner join 
(select ID,count(*) as MostComments from TableA
group by ID) a
on a.ID=b.ID
inner join TableC c
on b.PLACE=c.PLACE
order by a.MostComments Desc