2013-01-01 236 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