2012-03-05 9 views
3

私はCodeIgniterでWebアプリケーションを構築しています。1つのSQLクエリで複数のカウントがあります

ユーザーは投稿を「愛する」または「憎む」ことができます。これらのアクションは、テーブルに格納されている次の列でpost_rating呼ば:

  • のuser_id
  • 評価post_idの
    • 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(); 
    
        } 
    
    } 
    
  • +0

    より賢明な評価方式は0になりますニュートラル、愛のために1、嫌いに-1。 –

    +0

    よろしくお願いします。私はそれを切り替えるかもしれない。ありがとう! – Leeloo

    +0

    このクエリではあまり違いはありませんが、後ほど便利です。 –

    答えて

    2

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

    面白いことに、正確に同じ2つのソリューションを正確に(最高秒まで)投稿しました。 –

    +0

    ありがとうございます。それは機能していますが、今は1つの投稿を返すだけです(以前はすべてを返す)。現在のモデルでOPを更新しました。何か案は? – Leeloo

    +0

    @Tim: 'p.post_idでグループを追加 ' –

    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