MYSQL在不同阶段获得COUNT个最高列值

时间:2020-07-11 03:03:33

标签: mysql

这是一个非常复杂的数据库。因此,我简化了结构以便于理解。

我有2张桌子 表A:交易

p_id     rev_count
1        1
2        1
3        1
1        1
1        1
1        2 (Gets incremented as it has reached max entries)
2        1
2        1
2        2 (Gets incremented as it has reached max entries)
1        2
2        2

表B:rev_countReference

p_id     rev_count
1        2
2        2
3        1

因此,基本上,表B将rev_count值存储为表A的引用。由于p_id仅接受3个事务,因此,每当p_id超过3个计数时,rev_count的值就会增加,下一个p_id条目的rev_count值将增加。 >

问题 我想获取每个p_id在最大rev_count中占用的事务数。

所需的输出:

p_id      used_rev
1         1
2         2
3         1

到目前为止已经尝试过:

不幸的是,我还不能为上述数据库示例编写代码。但是到目前为止,我一直在尝试使用实际代码。


public function getfreeslots($user_id) {
        
        $this->db->select('count(t.id), t.reinvest_count, MAX(t.reinvest_count) AS max_reinvest, COUNT(t.id) AS outstandingSlots'); 
        $this->db->from('transactions t'); 
        $this->db->join('reinvestCount rc', "t.receiver_id=rc.user_id AND t.phase_id=rc.phase_id",'LEFT'); 
        $this->db->where('t.receiver_id', $user_id);
        
        $this->db->having('t.reinvest_count >= max_reinvest');
        $this->db->group_by('t.phase_id');
        $this->db->order_by('t.phase_id', 'ASC');
        
        $query = $this->db->get(); 
        $row = $query->result();
        
        if (empty($row))
            return FALSE;
        return $row;
        
    }
    
    

我正在使用Codeigniter查询构建器。因此,使用查询生成器的答案将不胜感激。

0 个答案:

没有答案
相关问题