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



我的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');
$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;
}
}

正如你所看到的,我正试图通过几个联接从Table1中获取title,并使用vegetable列进行搜索。因此,我遇到的问题是,如果在Table2中,id包含2个vid,并且两者都在$veg数组中,则会导致结果重复,因为即使是相同的id,项目也会出现两次。所以我的问题是如何防止它重复?

示例:$veg将是一个数组,因此对于该示例,假设它具有以下值potatoecabbagelettuce,并且第三表中的这些值中的每一个将分别具有以下值:123。现在我的问题是,如果我在一个id上重复vid,我将多次显示title,所以说id1,这有12vidtitle将重复两次,因为它被找到了两次。

尝试在活动记录查询中添加$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();

活动记录手册示例

$this->db->distinct();
$this->db->get('table');
// Produces: SELECT DISTINCT * FROM table

请参阅活动Reocord参考

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

PHP:array_unique-手动PHP函数从数组中删除重复项。

最新更新