SQL query to match a comma-separated string against a comma-separated string?

前端 未结 3 1751
长情又很酷
长情又很酷 2020-12-22 04:57

The MySQL query below uses PHP to pull in the $sector, which is a single digit, and the $subsector_text, which is a comma separated string. The $subsector_text could be a

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-22 05:56

    Your approach is correct, but need some modifications. Instead of try to match in only one condition (REGEXP), can create multiple conditions joined with OR...

    Example:

    $subsectorArray = explode(',', $subsector_text);
    $or = [];
    foreach ($subsectorArray as $subsector){
        $or[] = "a.subsector REGEXP '[^[:alnum:]]{$subsector}[^[:alnum:]]|^{$subsector}[^[:alnum:]]|[^[:alnum:]]{$subsector}$|^{$subsector}$'";
    }
    $orStr = implode(' OR ', $or);
    
     $sql = "
    SELECT DISTINCT a.id
                  , a.name
                  , a.category_id
                  , a.sector
                  , a.subsector
                  , a.year_in_operation
                  , a.state
                  , a.total_value
                  , b.country_id
                  , b.project_id
                  , c.isocode_3
                  , c.name
               FROM com_barchan_project a
               JOIN com_barchan_location b
                 ON b.project_id = a.id
               JOIN com_barchan_country c
                 ON c.id = b.country_id
               JOIN com_barchan_project_value_join d
                 ON a.id = d.project_id
              WHERE a.state = 1 
                AND a.sector = '$sector'
                AND ($orStr)
              ORDER 
                 BY a.total_value DESC
                  , a.category_id ASC
                  , a.name ASC
    ";
    

提交回复
热议问题