Ebad ghafoory Ebad ghafoory - 5 months ago 17
SQL Question

Mysql select sum() from another table

I have this tables :

Table: Articles

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


Table: Likes

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


i want get this result:

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


I use LEFT JOIN between two tables but this return records per
likes
table. so i get three record of article 1

My code:

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


I know that i must use
SUM()
but i didn't know how use it

With your answers i find that i must use this:

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


But i want to set filter in query. so use this :

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


But above code doesn't return any result

Answer

This is your query

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

Output is enter image description here