2016-09-22 53 views
0

我想这一点:多加入与在那里,喜欢和or_like 3笨的活动记录

 $location = 'a'; 
     $this->db->select('l.id, d.guests, l.city, l.country'); 
     $this->db->from('offers as o'); 
     $this->db->join('location as l', 'l.id = o.id', 'left'); 
     $this->db->join('desc as d', 'd.offer_id = o.id', 'left'); 
     $this->db->where('d.guests', $guests); 
     $this->db->where('o.completed', 1); 
     $this->db->where('l.country LIKE', $location.'%'); 
     $this->db->or_where('l.city LIKE', $location.'%'); 
     $this->db->limit(5); 

而且我有3位客人,并与国家阿尔巴尼亚(每桌1行吧)的报价。但是,如果$guests = 2;我有这1行的结果。同样,如果我使用likeor_like而不是whereor_where。如果我评论这一行:

$this->db->or_where('l.city LIKE', $location.'%');

一切工作正常,我如果$guests != 3和1行的结果,如果$guests = 3没有结果。

生成的查询与$this-db->last_query()是:

SELECT 'l'.'id', 'd'.'guests', 'l'.'city', 'l'.'country' FROM 'offers' as 'o' LEFT JOIN 'location' as 'l' ON 'l'.'id' = 'o'.'id' LEFT JOIN 'desc' as 'd' ON 'd'.'id' = 'o'.'id' WHERE 'd'.'guests' = 3 AND 'o'.'completed' = 1 AND 'l'.'country' LIKE 'a%' OR 'l'.'city' LIKE 'a%' LIMIT 5

我怎样才能让这个查询? 选择已完成的值= 1,客人= $guests以及城市或国家/地区$location

回答

1

试试这个代码

$location = 'a'; 
$this->db->select('l.id, d.guests, l.city, l.country'); 
$this->db->from('offers as o'); 
$this->db->join('location as l', 'l.id = o.id', 'left'); 
$this->db->join('desc as d', 'd.offer_id = o.id', 'left'); 
$this->db->where('d.guests', $guests); 
$this->db->where('o.completed', 1); 
$this->db->where("(l.country LIKE '".$location."%' or l.city LIKE '".$location."%')"); 
$this->db->limit(5); 
+0

'您的SQL语法错误;检查与您的MySQL服务器版本相对应的手册,以在'%或'l'.city'附近使用正确的语法。LIKE a%)LIMIT 5'' – gdfgdfg

+0

我已更新我的答案 – parth

0

您需要使用Query grouping

$location = 'a'; 
$this->db->select('l.id, d.guests, l.city, l.country'); 
$this->db->from('offers as o'); 
$this->db->join('location as l', 'l.id = o.id', 'left'); 
$this->db->join('desc as d', 'd.offer_id = o.id', 'left'); 
$this->db->where('d.guests', $guests); 
$this->db->where('o.completed', 1); 
$this->db->->group_start(); 
$this->db->where('l.country LIKE', $location.'%'); 
$this->db->or_where('l.city LIKE', $location.'%'); 
$this->db->group_end(); 
$this->db->limit(5); 

另外,还要看看like and or_like方法来避免这样的'l.country LIKE'代码。

0

试试这个

$location = 'a'; 
$this->db->select('l.id, d.guests, l.city, l.country'); 
$this->db->from('offers as o'); 
$this->db->join('location as l', 'l.id = o.id', 'left'); 
$this->db->join('desc as d', 'd.offer_id = o.id', 'left'); 
$this->db->where('d.guests', $guests); 
$this->db->where('o.completed', 1); 
$this->db->like('l.country',$location,'after'); 
$this->db->or_like('l.city',$location,'after'); 
$this->db->limit(5);