繁体   English   中英

一个SQL查询中有多个计数

[英]Multiple counts in one SQL query

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

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

  • ID
  • 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表,但是我怎样才能在标题,内容等相同的数组中返回爱与恨的数量呢?

谢谢!

:)

UPDATE!

这是我目前的模特:

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 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

您可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM