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 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题