商店表:
+--+-------+--------+
|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)类别的商店,我会得到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 :(得分: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();