【问题标题】:Not getting correct SUM amount for users votes from thread and reply table未从线程和回复表中获得用户投票的正确 SUM 金额
【发布时间】:2016-10-15 05:37:57
【问题描述】:

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

线程表

回复表

【问题讨论】:

    标签: codeigniter


    【解决方案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");
    

    经过测试并正常工作

    检查屏幕截图:-

    使用 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();
    

    【讨论】:

    • 只需检查查询并让我知道它是否给出正确的输出,然后我将在 CI 中转换它
    • 为什么你不想使用 $this->db->query()
    • @wolfgang1983 嘿检查我添加了活动记录查询
    • 我还有另一个解决方案,我的答案是使用活动记录。
    【解决方案2】:

    另一个使用$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;
        }
    }
    

    【讨论】:

      【解决方案3】:

      当您使用左连接时,它将从左表返回匹配的列和所有其他不匹配的列。使用 inner join 并检查您的结果。

      【讨论】:

        猜你喜欢
        • 2019-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-17
        • 2011-04-21
        • 2021-09-30
        • 1970-01-01
        • 2018-10-09
        相关资源
        最近更新 更多