Mysql从另一个表中选择sum()

时间:2016-06-10 12:53:22

标签: php mysql join sum left-join

我有这张表:

表:文章

   id   |   title   |   display   |
 -----------------------------------
    1   |   Fkekc   |      1      |
    2   |   ldsdf   |      1      |
    3   |   OTRld   |      0      |
    4   |   QCRSA   |      1      |

表:喜欢

   id  |  article_id |   like   |  type
 ----------------------------------------
    1   |      1     |   121    |   1
    2   |      1     |   652    |   2
    3   |      2     |   12     |   1
    4   |      1     |   5      |   3

我想得到这个结果:

Article [1] => 778
Article [2] => 12
Article [3] => 0
Article [4] => 0

我在两个表之间使用LEFT JOIN但这会返回每个likes表的记录。所以我得到了第1条的三条记录

我的代码:

 SELECT articles.*,likes.like FROM `articles` LEFT JOIN `likes` ON articles.id=likes.article_id WHERE display='1'

我知道我必须使用SUM(),但我不知道如何使用它

根据你的回答,我发现我必须使用这个:

SELECT articles.*, sum(likes.like) as likesSum FROM `articles` LEFT JOIN `likes`ON articles.id=likes.article_id WHERE display='1' GROUP BY articles.id

但我想在查询中设置过滤器。所以用这个:

SELECT articles.*, sum(likes.like) as likesSum FROM `articles` LEFT JOIN `likes`ON articles.id=likes.article_id WHERE display='1' && likesSum>='100' GROUP BY articles.id

但上面的代码不会返回任何结果

5 个答案:

答案 0 :(得分:2)

这是您的查询

SELECT articles.*,COALESCE(sum(likes.like),0) as total_like  FROM 
`articles` LEFT JOIN `likes` ON articles.id=likes.article_id group by   
articles.id

输出为enter image description here

答案 1 :(得分:1)

  SELECT articles.*, sum(likes.like) as likesSum FROM `articles` LEFT JOIN `likes`ON articles.id=likes.article_id WHERE display='1' GROUP BY articles.id

答案 2 :(得分:1)

这应该对你有用..

SELECT articles.id, sum(likes.like) from articles left join likes on (articles.id=likes.article_id) group by articles.id order by articles.id

请参阅使用GROUP BY

的SUM()

答案 3 :(得分:0)

你做的一切都正确,但只有一个失踪了。您应该使用分组

SELECT articles.*, likes.like 
FROM `articles` 
LEFT JOIN `likes` ON articles.id = likes.article_id 
WHERE display = '1' 
GROUP BY likes.article_id

答案 4 :(得分:0)