2017-09-06 97 views
0

我在查询一个条件,我要搜索的结果。 在数据库中有区域列,其中区域保存为逗号分隔。 和用户选择多个区域,我用逗号分隔的格式。 如何比较列值和搜索值。 我想在codeigniter中查询。MySQL查询的逗号分隔的搜索关键词列和ASLO值

$search_id2 = "01,02,03"; 

$this->db->select('posting_id,short_desc, doc_last, country'); 
$this->db->from('abc'); 
$this->db->like('region', $search_id2); 
$query = $this->db->get(); 
+1

你有机会摆脱逗号分离的数据,并正常化您的数据呢?如果是的话,那就麻烦你了 –

+0

是,第一规范化数据库。这将使编码这些事情变得更容易。 –

+0

因为在不同的功能,我不能做的数据库更改使用同一列这是不可能的。 –

回答

1

我只是试着回答你的问题。 您可以使用explode()

$search_id2 = "01,02,03"; 
$search_id2 = explode(",",$search_id2) 
$this->db->select('posting_id,short_desc, doc_last, country'); 
$this->db->from('abc'); 
foreach ($search_id2 as $key) { 
    $this->db->or_like('region', $key); 
} 
$query = $this->db->get(); 
+0

实际上是行不通的 - 因为如果他有区码在他的分贝01,02,03,003,004,005和你正在寻找“01,02,03”你还用那些匹配003 – sintakonte

0

为neodan的意见建议你可以使用find in set

这样的事情应该做的工作

$search_id2 = "01,02,03"; 
$arrSearchIds = explode(",",$search_id2); 

$this->db 
    ->select('posting_id,short_desc, doc_last, country') 
    ->from('abc') 
    ->group_start(); 

if (count($arrSearchIds) > 0) 
{ 
    foreach($arrSearchIds AS $id) 
    { 
     $this->db->or_where("find_in_set(".$id.", region)", NULL, false); 
    } 
} 
$this->db->group_end(); 
$query = $this->db->get();