如何计算左连接行?

时间:2012-12-14 15:48:58

标签: mysql

我有两张桌子:

articles:
id
title
text
timestamp

articles_views:
id
article_id
timestamp

我需要sql查询,它将返回由该文章的articles_views计数排序的所有文章的列表。

2 个答案:

答案 0 :(得分: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)

这将解决您的问题 -

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