2013-01-01 234 views
1

商店表:不同/連接兩個表

+--+-------+--------+ 
    |id|name |date | 
    +--+-------+--------+ 
    |1 |x  |March 10| 
    +--+-------+--------+ 
    |2 |y  |March 10| 
    +--+-------+--------+ 

類別表:

+--+-------+ 
|id|title | 
+--+-------+ 
|1 |tools | 
+--+-------+ 
|2 |foods | 
+--+-------+ 

店類別表(shop_cats):

+--+-------+--------+ 
|id|shop_id|cat_id | 
+--+-------+--------+ 
|1 |1  |1  | 
+--+-------+--------+ 
|2 |1  |2  | 
+--+-------+--------+ 

我想按類別商店(類別存儲在$ cat數組中)

 $this->db->select('shops.*'); 
    $this->db->from('shops'); 
    if(!empty($cat)) 
    { 
     $this->db->join('shop_cats' , 'shop_cats.shop_id = shops.id'); 
     $this->db->where_in('shop_cats.cat_id' , $cat); 
    } 


    $this->db->limit($limit , $offset); 
    $res = $this->db->get(); 

我的問題是,它返回重複的結果 例如,在該表中

+--+-------+--------+ 
|id|shop_id|cat_id | 
+--+-------+--------+ 
|1 |1  |1  | 
+--+-------+--------+ 
|2 |1  |2  | 
+--+-------+--------+ 

,如果我想用(1,2)I類獲得ID = 1號店的商店,兩次。 我希望它只返回每個商店一次而沒有任何重複。

我已經嘗試過通過

if(!empty($cat)) 
     { 
      $this->db->join('shop_cats' , 'shop_cats.shop_id = shops.id'); 
      $this->db->group_by('shop_cats.shop_id'); 
      $this->db->where_in('shop_cats.cat_id' , $cat); 
     } 

使用組也沒有工作,我也試着

if(!empty($cat)) 
     {   $this->db->select('DISTINCT shop_cats.shop_id'); 
      $this->db->join('shop_cats' , 'shop_cats.shop_id = shops.id'); 
      $this->db->where_in('shop_cats.cat_id' , $cat); 
     } 

,但我得到語法錯誤!

+0

什麼是您預期的結果? –

+0

@ shiplu.mokadd.im我希望它只返回一次商店,現在它會加入cat_shop表到商店,它不在乎它是否已經加入 – max

回答

1

嘗試

$this->db->distinct('shops.*'); 
$this->db->from('shops'); 
$this->db->join('shop_cats', 'shop_cats.shop_id = shops.id', 'left'); 
$this->db->where('shop_cats.cat_id', $cat); 
$this->db->limit($limit , $offset); 
$res = $this->db->get(); 
+0

thanx它不起作用,distinc doesn' t甚至顯示在查詢中,當我打印出最後一個查詢 – max

+0

@max我已經測試了查詢並正常工作。也許你的錯誤是在你的代碼中的其他地方。另外它不是特別的。你的代碼中是否有正確的代碼? – mallix