没有为用户从线程和回复表中获得正确的SUM金额

时间:2016-10-15 05:37:58

标签: codeigniter

我使用的是codeigniter 3.1.0,我试图从不同的表中获取两列的总和

如果我的 user_id = 1 ,则应返回 421 的总和,但返回 431 它正在添加其他用户的投票回复表

  

问题使用Active Record如何确保SUM为用户ID获取正确的金额。

模型功能

public function thread_reputation($user_id) {
    $this->db->select('SUM(reply.votes + thread.votes) AS reputation');
    $this->db->from('thread', 'left');
    $this->db->join('reply', 'reply.user_id = thread.user_id', 'left');
    $this->db->where('thread.user_id', $user_id);
    $this->db->where('reply.user_id', $user_id);
    $query = $this->db->get();

    if ($query->num_rows() > 0) {
        return $query->row();
    } else {
        return 0;
    }
}

控制器部分,我回应它

$thread_reputation = $this->thread_analytics_model->thread_reputation('1');
echo $thread_reputation->reputation;

主题表

enter image description here

回复表

enter image description here

3 个答案:

答案 0 :(得分:1)

使用此

更改您的查询
$query = $this->db->query("SELECT SUM(A.votes) as reputation from
    (
      SELECT reply.votes FROM reply where reply.user_id = $user_id

      UNION ALL

      SELECT thread.votes FROM thread where thread.user_id = $user_id               
    )AS A");

经过测试并正常工作

检查屏幕截图: - enter image description here

使用 ACTIVE REOCRD

进行查询
$this->db->select("SUM(A.votes) as reputation");
$this->db->from("(
SELECT reply.votes FROM reply where reply.user_id = $user_id

UNION ALL

SELECT thread.votes FROM thread where thread.user_id = $user_id) AS A");
$query = $this->db->get();

答案 1 :(得分:0)

使用$this->db->get_compiled_select();

的另一种解决方案
public function reputation($user_id) {
    $this->db->select('thread.votes');
    $this->db->from('thread');
    $this->db->where('thread.user_id ='  . $user_id);
    $thread_query = $this->db->get_compiled_select();
    $this->db->select('reply.votes');
    $this->db->from('reply');
    $this->db->where('reply.user_id ='. $user_id);
    $reply_query = $this->db->get_compiled_select();

    $query = $this->db->query("SELECT SUM(total.votes) as reputation from ($reply_query UNION ALL $thread_query) as total");

    if ($query->num_rows() > 0) {
        return $query->row();
    } else {
        return 0;
    }
}

答案 2 :(得分:-2)

当您使用左连接时,它将返回匹配的列&左表中所有其他不匹配的列。使用内部联接&检查你的结果。