문제

I've researched this but couldn't find a solution for my specific problem.

I have a column containing data in a certain format. Here are some examples:

1
6
14
1;6;14;16
etc...

I need a mysql statement which for example it will select all columns where 16 occurs.

I've tried this but it's also selecting columns where 1 and 6 occur:

"SELECT * FROM tbl WHERE kategorien LIKE '%".$_GET['katid']."%' AND status = 1 ORDER BY pos ASC"

Thanks in advance for any help!

도움이 되었습니까?

해결책 2

You could use MySQL function FIND_IN_SET:

SELECT * FROM tbl
WHERE
  FIND_IN_SET('16', REPLACE(kategorien, ';', ','))>0

however, it is usually not a good idea to store comma separated values in a single field, please have a look at this question: Is storing a delimited list in a database column really that bad?

다른 팁

You can try creating a helper function like this:

// Helper function
function getLike($str, $deliminator = ';', $field = 'kategorien') {
    if (false !== strpos($str, $deliminator)) {
        $strParts = explode($deliminator, $str);
        return "($field LIKE '%". implode("%' OR $field LIKE '%", $strParts) . "%')";
    } else {
        return "$field LIKE '%$str%'";
    }
}

// Debug
var_dump(getLike('1;6;14;16'));

Outputs:

string '(kategorien LIKE '%1%' OR kategorien LIKE '%6%' OR kategorien LIKE '%14%' OR kategorien LIKE '%16%')' (length=100)

In your query, you'd use it like this:

"SELECT * FROM tbl WHERE ". getLike($_GET['katid']) ." AND status = 1 ORDER BY pos ASC"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top