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