我有三张桌子; user
,car
和user_x_car
。 user_x_car
拥有拥有汽车的用户;存储user_id
和car_id
。我想让没有车的用户如下:
$car_owner = $this->db->select()->from('user_x_car')->get()->result();
for ($i = 0; $i < count($car_owners); $i++)
$car_owner_id[$i] = $car_owner[$i]->user_id;
$non_car_owner = $this->db->select()->from('user')->where_not_in('id', $car_owner_id)->get()->result();
我得到了我想要的东西,但是,有没有办法绕过中间的for循环创建和在第一个选择中选择的id数组。有没有办法直接获取所选user_id
的数组?
答案 0 :(得分:1)
你可以通过两个查询来完成,比如
第一个从user_x_car表中获取所有ID
$temp1=array();
$temp=$this->db->distinct()->select('user_id')->get('user_x_car')->result_array();
然后从用户表中获取那些没有汽车的用户
foreach($temp as $each)
{
array_push($temp1,$each['user_id']);
}
$rs=$this->db->where_not_in('id',$temp1)->get('user');
if($rs->num_rows()>0)
{
$data=$rs->result_array();
print_r($data);die;
}
$ data将打印所有没有车的用户。如果您遇到任何问题,请告诉我。
答案 1 :(得分:1)
function get_unread_notifications_ids()
{
//get unread notifications ids
$this->db->select('GROUP_CONCAT(fknotification_id) as alll');
$this->db->from("te_notification_status_tbl");
$this->db->where('read_status',0);
$ids=$this->db->get()->row();
return $idss=str_replace(",","','",$ids->alll);
}
和第二个函数是这样的:
function get_unviewed_photos_events(){
$idss = $this->get_unread_notifications_ids();
$this->db->select('img.*',False);
$this->db->from("te_notifications_tbl notif");
$this->db->join('te_images_tbl img','img.id=notif.reference_id','LEFT OUTER');
$this->db->where("notif.id IN('".$idss."')");
$rslt = $this->db->get()->result_array();
return $rslt;
}
答案 2 :(得分:0)
查询
$non_car_owner = $this->db->query('SELECT user.*
FROM user LEFT JOIN user_x_car ON user_x_car.id=user.id
WHERE table2.id IS NULL')->result();
此处不在桌面上的用户user_x_car
foreach($non_car_owner as $user){
echo $user->user_id;
}