问题描述
我想从 2 个不同的表中选择 id 并使用两个表中都存在的 id。
卖家
id | name | mobile_number | password | is_active
1 | abc | 987654321 | 12345678 | 0
2 | pqr | 989898989 | 12345678 | 1
3 | lmn | 919191991 | 12345678 | 1
其中,0 未激活,1 处于激活状态。
油轮
id | seller_id | capacity
1 | 1 | 14
2 | 2 | 7
3 | 2 | 3.5
4 | 3 | 3.5
其中,seller_id 是外键。
现在,我想选择所有状态为 active 即 is_active = 1 且容量 = 3.5 的卖家
这是我的代码。
$data = $this->db->select('id')
->from('seller')
->where('is_active',1)
->get()
->result();
return $data;
}```
```public function check_capacity($id,$capacity){
$data=$this->db->select('seller_id',$idd)
->from('tanker')
->where('capacity',$capacity)
->get()
->result();
return $data;
}```
Expected Output :
*Array
(
[0] => stdClass Object
(
[id] => 2
)
[1] => stdClass Object
(
[id] => 3
)
)*
解决方法
您必须将这两个表连接在一起:
$this->db->select('*,seller.id as seller_id,tanker.id as tanker_id')
->from('seller')
->join('tanker','seller.id = tanker.seller_id')
->where('is_active',1)
->where('capacity',3.5)
->get()
->result();
一旦你有了这个,你就可以使用参数(例如选择一个动态容量)。如果您遇到问题,请注意您始终可以使用以下方法打印最后一个查询:
print $this->db->last_query();