2012-12-14 74 views
2

我有2個表:如何計算左連接的行數?

articles: 
id 
title 
text 
timestamp 

articles_views: 
id 
article_id 
timestamp 

我需要SQL查詢這將返回由articles_views下令所有物品的清單計算該文章。

回答

5
SELECT 
    a.id 
    , a.Title 
    , COUNT(v.id) 
FROM 
    articles a 
LEFT JOIN 
    article_views v 
ON a.id = v.article_id 
GROUP BY 
    a.id, a.title 
ORDER BY 
    COUNT(v.id) DESC 
+1

+1你的答案是我之前是正確的。 – swasheck

1

這將解決您的problem-

SELECT articles.*, 
(select count(*) from `articles_views` C where P.id = C.article_id) as CNT 
FROM articles P inner join articles_views C 
    ON P.id = C.article_id group by P.id 
order by cnt desc