简体   繁体   中英

distinct/join two table

shops table:

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

category table :

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

shop categories table (shop_cats):

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

i want to get shops by category (categories are stored in the $cat array)

     $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();

my problem is it returns duplicate results for example in this table

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

if i want shops with (1,2) category i get shop with id = 1 , twice . i want it to return each shop only once without any duplicate .

i've tried to use group by

 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);
         }

it didn't work , i've also tried

 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);
         }

but i get syntax error !

Try

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM