2012-03-05 55 views
3

我正在用CodeIgniter构建一个Web应用程序。一次SQL查询中的多次计数

用户可以“爱”或“讨厌”帖子。这些行动都存储在一个表中调用与下面的列post_rating:

  • ID
  • 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表,但我怎么会去还回的爱和讨厌与标题,内容等在同一阵列中计数?

谢谢!

:)

更新!

这是我此刻的MODEL:

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

一个更合理的评价机制将是0中性,1代表爱,-1代表仇恨。 – 2012-03-05 20:33:27

+0

好的电话。我可能会将其切换。谢谢! – Leeloo 2012-03-05 20:40:37

+0

在这个查询中没有多少区别,但是您可能会发现'SUM(rating)'有用:) – 2012-03-05 20:44:52

回答

2

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

有趣的是,我们在同一时间发布了两个稍微不同的解决方案(精确到秒) – 2012-03-05 20:15:17

+0

谢谢,队友。它正在工作,但现在它只返回一个帖子(之前它将全部返回)。我用当前的模型更新了OP。有任何想法吗? – Leeloo 2012-03-05 20:29:39

+0

@Tim:通过p.post_id添加'group' – 2012-03-05 20:31:43

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