5

用不同数量的 WHERE 条件构造 sql 的最佳方法是什么?我的解决方案看起来很难看:

my ($where, @values);
if ($phone_number)
{
    $where = 'AND pnone_number=?';
    @values = ($from, $till, $phone_number);
}
else 
{
    $where = '';
    @values = ($from, $till);
}
my $sql = 'SELECT * FROM calls WHERE time between ? AND ? '.$where.' ORDER BY time';
my $res = $dbh->selectall_arrayref($sql, undef, @values) or warn 'error';
4

3 回答 3

10

怎么样:

my $where = '';
my @values = ( $from, $till );

if ( $phone_number ) { 
    $where = 'AND phone_number=?';
    push @values, $phone_number;
}

这消除了对您的else条款的需要。

你也可以使用类似SQL::Abstract的东西。

use SQL::Abstract;

...

my ( $sql, @values ) = SQL::Abstract->new->select(
    'calls',                                                    # table
    '*',                                                        # columns
    { time => { '<=' => $till, '>' => $from },                  # where clause
      $phone_number ? ( phone_number => $phone_number ) : ( ),
    },
    'time'                                                      # order clause
);
于 2013-05-20T08:18:58.517 回答
1

1=1$where为epmty的情况添加。

my $where = "AND time between ? AND ? ";
my @values = ($from, $till);

if ($phone_number) {
    $where .= 'AND pnone_number=? ';
    push @values, $phone_number;
}

my $sql = 'SELECT * FROM calls WHERE 1=1 $where ORDER BY time';
my $res = $dbh->selectall_arrayref($sql, undef, @values) or warn 'error';
于 2013-05-20T09:24:06.020 回答
0

条件列表包括(又名“企业”):

my @values = ( $from,
               $till,
               ( $phone_number ) x !! $phone_number,
             );

my $sql = 'SELECT * FROM calls WHERE time between ? AND ? '
        . 'AND phone_number=?' x !! $phone_number
        . ' ORDER BY time';
于 2013-05-20T11:30:21.390 回答