php - 一个 SQL 查询中的多个计数

标签 php sql codeigniter

我正在使用 CodeIgniter 构建 Web 应用程序。

用户可以“喜欢”或“讨厌”帖子。这些操作存储在名为 post_rating 的表中,其中包含以下列:

  • 编号
  • post_id
  • 用户编号
  • 评分

评级可以是 0 表示中立、1 表示喜欢或 2 表示讨厌。

在我的模型中,我使用以下函数返回了每个帖子的一些基本信息:

function get_posts($thread_id)

{

    $this->db->select('id, user_id, date_posted, content');
    $this->db->from('post');
    $query = $this->db->get();

    if ($query->num_rows() > 0)

    {

        return $query->result();

    }

}

我知道我需要加入 post_rating 表,但我如何才能在与标题、内容等相同的数组中返回爱恨计数?

谢谢!

:)

更新!

这是我目前的模型:

function get_posts($thread_id)

{

    $this->db->select('post.id, post.user_id, post.date_posted, post.content, post.status_visible, user.username, user.location, user.psn, user.clan, user.critic, user.pro, SUM(case when rating = 1 then 1 end) as love, SUM(case when rating = 2 then 1 end) as hate');
    $this->db->from('post');
    $this->db->join('user', 'user.id = post.user_id', 'left');
    $this->db->join('post_rating', 'post_rating.post_id = post.id', 'left');
    $this->db->where('thread_id', $thread_id);
    $this->db->order_by('date_posted', 'asc');
    $query = $this->db->get();

    if ($query->num_rows() > 0)

    {

        $this->db->select('id');
        $this->db->from('post_vote');

        return $query->result();

    }

}

最佳答案

您可以使用一个案例来总结两个不同的统计数据:

select  title
,       content
,       sum(case when pr.rating = 1 then 1 end) as Love
,       sum(case when pr.rating = 2 then 1 end) as Hate
,       (
        select  count(*)
        from    posts up
        where   up.user_id = p.user_id
        ) as UserPostCount
from    posts p
left join
        posts_rating pr
on      pr.post_id = p.post_id
group by
        title
,       content
,       user_id

关于php - 一个 SQL 查询中的多个计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9573229/

相关文章:

sql - PostgreSQL 查询,LIKE 运算符

java - MySQL 查询结果很慢

java - CodeIgniter 将类加密为 java

php - Codeigniter 事件记录 - 使用数组中的数据更新查询

php - 如何显示从该表单中选择的数据?

php - 如何在不迁移特定框架的情况下进行数据库版本控制?

php - 如何在 PHP 脚本中返回行号

php - laravel Eloquent 一对多关系返回null

java - JOOQ:如何将记录映射到别名表(来自嵌套查询)

php - 如何在 CodeIgniter 库中获取用户 ID