Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用CI的where in语句防止重复结果_Php_Mysql_Sql_Codeigniter - Fatal编程技术网

Php 使用CI的where in语句防止重复结果

Php 使用CI的where in语句防止重复结果,php,mysql,sql,codeigniter,Php,Mysql,Sql,Codeigniter,我的where insql语句有问题。我会先展示我的表格,然后解释我想做什么以及为什么我会遇到这个问题 Table1 id primary key title Table2 id primary key vid foreign key Table3 vid primary key vegetable 上面是我的表,下面是我的CodeIgniter SQL $this->db->select('*'); $this->db->from('Table1');

我的
where in
sql语句有问题。我会先展示我的表格,然后解释我想做什么以及为什么我会遇到这个问题

Table1

id primary key
title


Table2

id primary key
vid foreign key


Table3

vid primary key
vegetable 
上面是我的表,下面是我的CodeIgniter SQL

$this->db->select('*');
$this->db->from('Table1');
$this->db->join('Table2', 'Table2.id = Table1.id');
$this->db->join('Table3', 'Table3.vid = Table2.vid');
$this->db->where_in('vegetable', $veg);
$query = $this->db->get();
$result = $query->result();
结果将返回到我的控制器,并发送到我的视图,在该视图中按如下方式输出:

if (isset($results)){
            foreach($results as $row){
                $id = $row->id;
                echo $row->title;
            }
}
如您所见,我正试图通过一些连接从
表1
中获取
标题
,并使用
蔬菜
列进行搜索。因此,我遇到的问题是,如果在
表2
id
包含2个
vid
s,并且两者都在
$veg
数组中,它将导致结果重复,因为即使是相同的
id
项,也会出现两次。所以我的问题是,我怎样才能防止它重复

例如:
$veg
将是一个数组,因此在本例中,让我们假设它具有以下值
potatoe
colla
莴苣
,并且第三个表中的每个值将分别具有以下值
1
2
3
。现在的问题是,如果我在一个
id
上重复
vid
,我会让
title
显示不止一次,所以说
id
1
,这有
vid
1
2
title
会重复两次,因为它被找到两次

if (isset($results)){
            $results = array_unique($results);
            foreach($results as $row){
                $id = $row->id;
                echo $row->title;
            }
}

php函数从数组中删除重复项。

尝试添加
$this->db->distinct()

$this->db->select('*');
$this->db->from('Table1');
$this->db->join('Table2', 'Table2.id = Table1.id');
$this->db->join('Table3', 'Table3.vid = Table2.vid');
$this->db->where_in('vegetable', $veg);
$this->db->distinct();
$query = $this->db->get();
$result = $query->result();
活动记录手册中的示例


遗憾的是,它不起作用,我在phpmyadmin中也尝试了它,以检查它是否与我的CI函数有关,但我仍然重复了这些值。虽然这里没有使用组函数,但您使用的是
$this->db->group_by(“Table1.id”)
如果可能的话,请给我一个文档,如果可能的话,请给我一个快速的解释,而不是解决它的不同的子句。你可以访问,看看它应该如何实际使用,在CI中,我已经给了你参考。这样做会返回一个错误
类stdClass的对象无法转换为string
$this->db->distinct();
$this->db->get('table');

// Produces: SELECT DISTINCT * FROM table