简体   繁体   English

搜索多个类别 (FIND_IN_SET)

[英]Search multiple categories (FIND_IN_SET)

I have project in Codeigniter where user can search thorugh mulitple categories.我在 Codeigniter 有项目,用户可以在其中搜索多个类别。 In my database, category field is comma separated string (46, 53, 76).在我的数据库中,类别字段是逗号分隔的字符串(46、53、76)。

When user select category in filters (46) and match with first category in database, it works fine but, if user select another category (53), query doesn't work properly.当过滤器(46)中的用户 select 类别并与数据库中的第一个类别匹配时,它可以正常工作,但是如果用户 select 另一个类别(53),查询将无法正常工作。 Similar problem ocure when user select multiple categories.当用户 select 多个类别时,也会出现类似的问题。

My code is something like:我的代码是这样的:

if(!empty($category)) {
        $cat_array = explode(',', $category);
        $count_items = count($cat_array);
        
        
        
        if($count_items == '1') {
            $this->db->where("find_in_set($category, po_category)");
        } else {
            
            
            
            
            
            
            
            $this->db->group_start();
            $count = 0;
            foreach($cat_array as $item) {
                $count++;
                
                if($count == '1') {
                    $this->db->where("find_in_set($item, po_category)");
                } else {
                    $this->db->or_where("find_in_set($item, po_category)");
                }
            }
            $this->db->group_end();
        }
    }

I wonder if 'find_in_set' works in this structure.我想知道“find_in_set”是否适用于这种结构。

In my database, category field is comma separated string ( '46, 53, 76' ).在我的数据库中,类别字段是逗号分隔的字符串( '46, 53, 76' )。

When user select category in filters ( 46 ) and match with first category in database, it works fine but, if user select another category ( 53 ), query doesn't work properly.当过滤器( 46 )中的用户 select 类别并与数据库中的第一个类别匹配时,它可以正常工作,但是如果用户 select 另一个类别( 53 ),查询将无法正常工作。

There is no 53 in your values list!您的值列表中没有53 It contains the value ' 53' (with leading space char) which differs from the value to be searched for.它包含与要搜索的值不同的值' 53' (带有前导空格字符)。 And hence your searching gives negative result.因此,您的搜索给出了否定的结果。

SELECT FIND_IN_SET(  53 , '46, 53, 76'),
       FIND_IN_SET( '53', '46, 53, 76'),
       FIND_IN_SET(' 53', '46, 53, 76');    

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=81f440fd21b450924f21e769039ad1db https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=81f440fd21b450924f21e769039ad1db

PS. PS。 Trailing spaces are taken into account too.尾随空格也被考虑在内。

There is space after comma in your po_category field.您的po_category字段中的逗号后有空格。

So you need to remove it.所以你需要删除它。

You can try like that.你可以这样试试。

$this->db->where("find_in_set($item, REPLACE(po_category, ' ', ''))");
$this->db->or_where("find_in_set($item, REPLACE(po_category, ' ', ''))");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM