提问者:小点点

如何从一个限制为1到列的表中选择所有数据


我有一个有2个记录的表和一个有多个记录与主表链接的明细表。

可以添加或删除记录。

我想要的是显示所有的2个记录时,当前用户角色不是18。

并且当当前用户角色为18时,仅显示主表中的1条记录,其详细信息表最大记录与用户ID为78的主记录链接。

这是我的代码:

$this->db->select('BaseTbl.*');
$this->db->from('table1 as BaseTbl');
if($this->roleId == '18'){
    $this->db->where('(select table2.userId from table2 where table2.masterId = BaseTbl.id ORDER BY table2.id DESC LIMIT 1)', '78');
}

到目前为止,我已经尝试过了:

$this->db->select('BaseTbl.*');
$this->db->from('table1 as BaseTbl');
$this->db->join('table2 as table2','table2.masterId = BaseTbl.id','left');
if($this->roleId == '18'){
    $this->db->where('table2.userId', $this->userId);
    $this->db->where('table2.id', 'max(id)');
}

现在显示userid78记录,但不是该特定主表记录的最新记录。


共1个答案

匿名用户

我设法得到了我想要的结果使用这个。

$this->db->select('BaseTbl.*');
$this->db->from('table1 as BaseTbl');
$this->db->join('table2 as table2','table2.masterId = BaseTbl.id','left');
if($this->roleId == '18'){
    $this->db->where('table2.userId', $this->userId);
    $this->db->where('table2.id = (select max(table2.id) from table2 where masterId = BaseTbl.id)');
}