【问题标题】:distinct/join two table不同/连接两个表
【发布时间】:2013-01-01 12:02:19
【问题描述】:

商店表:

   +--+-------+--------+
    |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 的商店,两次。 我希望它只返回每家商店一次,没有任何重复。

我尝试使用 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);
         }

没用,我也试过了

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

但我得到语法错误!

【问题讨论】:

  • 您的预期结果是什么?
  • @shiplu.mokadd.im 我希望它只返回每个商店一次,现在它会将 cat_shop 表加入商店并且它不在乎它是否已经加入

标签: php mysql codeigniter activerecord


【解决方案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();

【讨论】:

  • thanx 它不起作用,当我打印出最后一个查询时,distinc 甚至没有显示在查询中
  • @max 我已经测试了查询并且工作正常。也许您的错误在您的代码中的其他地方。它也不是不同的,它是不同的。你的代码中正确吗?
猜你喜欢
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 2019-08-11
  • 2011-04-07
  • 2014-11-02
相关资源
最近更新 更多