doutu6658 2016-10-14 11:14
浏览 67
已采纳

在codeigniter中进行多个查询,结果基于第一个查询

I want to display all rows of table article, and for each of article row i want get the SUM of votes from another table (likes), and this with one query.

Here what i have:

$query = "SELECT article.title,article.tags,article.description,article.slug,users.username,article.photo,article.id,article.date,SUM(likes.votes) as upvotes
          FROM article";
$query .= " LEFT JOIN users ON article.user_id = users.user_id ";
$query .= " LEFT JOIN likes ON likes.article_id = article.id ";

But my problem with this query, i get only one row ! because in table likes there only one row ...

I want to display results based on article table (i have about 50 rows in it)... and if there nothing related to votes for a specific article, we show (0 votes).

Thank you.

  • 写回答

2条回答 默认 最新

  • doudao3170 2016-10-14 13:21
    关注

    Add group by to the code :

    $query = "SELECT article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date, SUM(likes.votes) as upvotes FROM article";
    $query .= " LEFT JOIN users ON article.user_id = users.user_id ";
    $query .= " LEFT JOIN likes ON likes.article_id = article.id ";
    $query .= " GROUP BY article.id";
    

    Or use codeigniter method:

    $this->db->select("article.title, article.tags, article.description, article.slug, users.username, article.photo, article.id, article.date");
    $this->db->select("SUM(likes.votes) as upvotes", false);
    $this->db->from("article");
    $this->db->join("users","article.user_id = users.user_id");
    $this->db->join("likes","likes.article_id = article.id");
    $this->db->group_by("article.id");
    $query = $this->db->get();
    return $query->result_array();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化