我正在用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中性,1代表愛,-1代表仇恨。 – 2012-03-05 20:33:27
好的電話。我可能會將其切換。謝謝! – Leeloo 2012-03-05 20:40:37
在這個查詢中沒有多少區別,但是您可能會發現'SUM(rating)'有用:) – 2012-03-05 20:44:52