日期:2014-05-18  浏览次数:20407 次

兩個表按照回復量排序怎麼寫sql?
t1(標題表)
id

t2(回復表1,會有多條回復,關係:t2.t1id=t1.id)
t1id
============
列出t1的數據,以回復數多少排序,怎麼寫?

------解决方案--------------------
select a.*,b.cnt as 回复数
from t1 as a
inner join (select t1id,count(*) as cnt from t2 group by t1id) as b on a.id=b.t1id
order by b.cnt desc

------解决方案--------------------
--?这样?
select t1.id from t1 join t2 on t1.id=t2.t1id group by t1.id order by count(*) desc
------解决方案--------------------
select t1.id ,count(1) from t1 left join t2 on t1.id=t2.t1id group by t1.id order by count(1) desc
------解决方案--------------------
select t1.id , count(*) 回复数 from t2,t1 where t2.t1id = t1.id group by t1.id order by 回复数 desc