What is the syntax for doing array searching as a parameter in MySQL?

12

What is the correct syntax, if possible, to pass an array as a parameter, using FIND_IN_SET more or less on this idea:

SELECT c.cpf FROM tbl_cliente as c WHERE FIND_IN_SET(array, c.cpf);
    
asked by anonymous 09.01.2014 / 14:38

2 answers

10

The function FIND_IN_SET() searches for one (first parameter) into a list of comma-separated elements declared in another String (second parameter).

Example:

mysql> SELECT FIND_IN_SET('b','a,b,c,d');
    -> 2

So if your array is a String with elements separated by commas, use it as follows:

SELECT c.cpf FROM tbl_cliente as c WHERE FIND_IN_SET(c.cpf, array);

or

SELECT c.cpf FROM tbl_cliente as c WHERE FIND_IN_SET(c.cpf, 'cpf1,cpf2,cpf3');

On the other hand, if you have a table with CPFs and want to check if the customer's CPF is in this table, use the IN clause, which accepts comma-separated value lists or a subselect. Example:

SELECT c.cpf FROM tbl_cliente as c WHERE c.cpf in ('xxx.xxx.xxx-xx', 'yyy.yyy.yyy-yy')

Or:

SELECT c.cpf FROM tbl_cliente as c WHERE c.cpf in (select cpf from tbl_outratabela)
    
09.01.2014 / 14:55
1

A solution with php would be to generate a query with several ? for IN() . and then pass the cpfs in the PDO execute ()

$sql ='SELECT c.cpf FROM tbl_cliente as c WHERE c.cpf IN(';

$qtd_cpfs = count($cpfs);
$in = str_repeat('?', $qtd_cpfs);
$in = preg_replace('/,$/', '', $in);

$sql .= $in .')';

//depois
$stmt = $db->prepare($sql);
$stmt->execute($cpfs);
    
09.01.2014 / 15:02