2012-03-05 52 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