【问题标题】:DBI selecting from tables all vs subset dataDBI 从表中选择所有数据与子集数据
【发布时间】:2014-02-19 14:48:19
【问题描述】:

如果定义了 $input,我有以下代码接受来自用户的输入:

代码将选择所有具有 field1= $input 的数据,否则代码将选择表中的所有数据

   if (defined $input) {

my $sth= $dbh->prepare("select field1,field2 from mytable where field1 = ?  ");
$sth->execute($value);}
    else {
    my $sth= $dbh->prepare("select field1,field2 from mytable");
$sth->execute();

  }

我将相同的代码复制到多个具有不同数据字段的表中。

我想知道 DBI 是否有一个选项可以将这 2 个查询合并为一个查询以更易于维护?

【问题讨论】:

  • 根据 $input 构建 $where 并将其附加到选择查询。

标签: perl dbi


【解决方案1】:

这是我通常的做法:

my (@where, @params);

if (defined $input) {
  push @where, 'field1=?';
  push @params, $input;
}

# push more clauses onto arrays as needed

my $sql="select field1,field2 from mytable";
if (@where) {
  $sql .= " WHERE ".join (' AND ',@where);
}

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

这样做的好处在于您可以根据需要添加任意数量的子句。

【讨论】:

  • join(' and ', @where)
  • @mpapec 是的,这就是我的意思
  • 可能是mytableWHERE的空间
【解决方案2】:

你不能这样做:

select field1,field2 from mytable where ((? is null) or (field1 = ?))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 2015-12-03
    相关资源
    最近更新 更多