reglas de marcador de posición de mysql perl

MySQL, Perl

The following select works fine with no placeholders, but doesn't with placeholders. It doesn't generate any SQL errors, but it returns all blanks/zeros - not the same counts as the same statement without placeholders.

my $sql="SELECT ?, SUM(IF(H1='1',1,0)) AS banner1 FROM table_name WHERE (?!='' and ? IS NOT NULL) GROUP BY ?";

my $sth = $dbh->prepare($sql);

my $variable = "Q1";

$sth->execute($variable, $variable, $variable, $variable);   

¿Qué estoy haciendo mal?

Am I trying to use placeholders in ways not intended? It works when I only use placeholders in the WHERE clause. It does not work when I use a placeholder in the SELECT or GROUP BY clause. Is that the issue - placeholders can only be used in the WHERE clause?

preguntado el 08 de noviembre de 11 a las 17:11

2 Respuestas

You can't use placeholders in the SELECT portion of an SQL statement. This is described in la documentación:

With most drivers, placeholders can't be used for any element of a statement that would prevent the database server from validating the statement and creating a query execution plan for it. For example:

"SELECT name, age FROM ?"         # wrong (will probably fail)
"SELECT name, ?   FROM people"    # wrong (but may not 'fail')

respondido 08 nov., 11:22

You can't use placeholders to substitute a column or table name. Even in your WHERE clause, it's not doing what you think it's doing. When you substitute Q1 for the placeholder, you get:

WHERE ('Q1'!='' and 'Q1' IS NOT NULL)

i.e. an expression that is always true.

respondido 08 nov., 11:22

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.