我正在用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