doumu2172 2016-06-10 12:53 采纳率: 0%
浏览 358
已采纳

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

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

  • 写回答

5条回答 默认 最新

  • duanqiangwu9332 2016-06-10 13:18
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀