我要"order by counts desc"
这句怎么加进去啊?
SELECT Article.Id, Article.Title, Article.AddTime, (select count(0) as counts from Comments where Article.Id=Comments.NewsId) AS counts
FROM Article
ORDER BY (select count(0) as counts from Comments where Article.Id=Comments.NewsId) desc
select Id,Title,AddTime,(select count(*) from Comments where Article.Id=Comments.NewsId) as counts from Article
order by counts desc
这都试过了
请有答案的测试后再回,谢谢!
楼上正解!
用一个变量代替counts试试。
SQL执行顺序:
SELECT A.Id,A.Title,A.AddTime,B.Counts FROM Article A LEFT JOIN (SELECT ISNULL(Count(1),0) AS Counts,NewsId FROM Comments GROUP BY NewsId) B ON A.Id=B.NewsId ORDER BY B.Counts DESC
楼主的sql语句性能较差,正确的方式是使用表连接的方法去实现。
表A是Article,表B需要我们根据Comments去构造。
sql语句可以参考xu_happy_you 。