【问题标题】:Multiple counts in one SQL query一个 SQL 查询中的多个计数
【发布时间】:2012-03-05 20:08:08
【问题描述】:

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

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

  • 身份证
  • post_id
  • user_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();

    }

}

【问题讨论】:

  • 更合理的评分方案是 0 表示中立,1 表示爱,-1 表示恨。
  • 好电话。我可能会切换它。谢谢!
  • 这个查询没有太大区别,但你可能会发现SUM(rating)以后有用:)

标签: php sql codeigniter


【解决方案1】:

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

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

【讨论】:

  • 有趣的是,我们同时发布了两个略有不同的解决方案(精确到秒)
  • 谢谢,伙计。它正在工作,但现在它只返回一个帖子(之前它已经返回了所有帖子)。我已经用我当前的模型更新了 OP。有什么想法吗?
  • @Tim: 添加group by p.post_id
  • 抱歉打扰了,但我如何在同一个查询中返回用户的总帖子数?我尝试将“SUM(post.user_id = post.user_id then 1 end)作为帖子的情况”添加到我的选择语句的末尾,但帖子数始终为 1。有什么想法吗?
  • 您可以为此使用子查询,并添加到答案中。如果子查询使用user_id,则user_id 必须是group by 的一部分。
【解决方案2】:
select p.post_id, 
       max(p.title) title,
       count(case pr.rating when 1 then 1 else null end) lovecount,
       count(case pr.rating when 2 then 1 else null end) hatecount
from YourPostsTable p 
left join post_rating pr on p.post_id = pr.post_id
group by p.post_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-17
    • 2010-11-19
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多