我有一个查询,在where语句中我想插入一个这样的三元运算符:
WHERE
$self->is_defined? 'some_column = $self->defined' : 'some_other_column = $self->defined_some'
AND blah blah blah
AND blah blah blah
这样的事情。怎么做?
截至目前,我的代码不起作用:
"SELECT blah blah blah
WHERE
"$self->is_defined ? 'o.project_id = "$self->project_id"' : 'o.brand_id = "$self->brand_id"'"
答案 0 :(得分:0)
首先,方法调用不会在双引号内插入,在单引号内更少。
在创建sql时应该使用占位符以避免sql injection,
my $sql = "SELECT * from ... WHERE ";
my ($cond, $val) = $self->is_defined
? ("some_column = ?", $self->defined)
: ("some_other_column = ?", $self->defined_some);
# constructing final sql..
$sql .= $cond;
my $st = $db_handle->prepare($sql) or die $db_handle->errstr;
$st->execute($val) or die $st->errstr;