【问题标题】:Perl script or MySQL fix?Perl 脚本或 MySQL 修复?
【发布时间】:2012-04-03 08:23:07
【问题描述】:

我是 Perl 的初学者,刚刚完成了一个使用 perl scipt 的调整任务。我现在关注的声明是:

my $sth = $dbh->prepare('SELECT StringValue FROM CustomData WHERE (Record_ID = \'' . $ref->{'Record_ID'} . '\' && Field_ID = \'' . $metadata[11] . '\') LIMIT 1;');

当前语句将提取与Record_ID 值匹配的每条记录。但是,需要将其更改为仅拉取 Record_ID 以数字 1、2、9 开头的记录

我认为这更像是一个正则表达式问题,对吗?如果是这种情况,我应该只修改

 Record_ID = \'' . $ref->{'Record_ID'}

部分。那是对的吗?或者这应该在prepare 语句中修复?

【问题讨论】:

  • 由于“limit 1”,它会拉取第一个匹配的记录。
  • 您应该使用占位符而不是尝试自己插入和引用变量。请参阅 DBI 文档。

标签: mysql regex perl


【解决方案1】:

您应该使用placeholders,而不是尝试插入变量并尝试自己引用。您甚至可以考虑为 '1%' 等使用占位符,除非您在所有查询中都认为它们是静态的。

my $sth = $dbh->prepare( q#
     SELECT StringValue FROM CustomData 
     WHERE (Record_ID = ? && Field_ID = ?) 
     AND (Record_ID LIKE '1%' OR Record_ID LIKE '2%' OR Record_ID LIKE '9%')
     LIMIT 1
#);

$sth->execute($ref->{'Record_ID'}, $metadata[11]);

【讨论】:

  • @TLP-您使用的是$dbh->execute,它必须是$sth->execute。此外,您的解决方案给了我关于单引号 Number found where operator expected at record.pl at line 的错误。即使我转义引号,我也会得到空白输出。
  • @Devendra 是的。现已修复。
【解决方案2】:

在 WHERE 子句中添加 AND-part 以过滤不需要的 Record_ID。

SELECT StringValue 
FROM CustomData \
WHERE (Record_ID = \'' . $ref->{'Record_ID'} . '\' && Field_ID = \'' . $metadata[11] . '\') 
AND (Record_ID  LIKE "1%" OR Record_ID  LIKE "2%" OR Record_ID  LIKE "9%")
LIMIT 1

【讨论】:

    【解决方案3】:

    为避免多次屏蔽',您可以使用qq

    my $sth = $dbh->prepare( qq§SELECT StringValue FROM CustomData 
                                WHERE (Record_ID = '$ref->{Record_ID}' AND 
                                       Field_ID = '$metadata[11]') LIMIT 1§
                           ) ;
    

    【讨论】:

      【解决方案4】:

      你是对的关于改变部分Record_ID = \'' . $ref->{'Record_ID'} . '\'

      将其替换为Record_ID LIKE \'1%\' || Record_ID LIKE \'2%\' || Record_ID LIKE \'9%\'

      删除LIMIT 1,这只匹配任何一行,无论是从1,2还是9开始

      这是我认为的解决方案

      my $sth = $dbh->prepare('
          SELECT StringValue 
          FROM CustomData 
          WHERE ( Record_ID LIKE \'1%\' || Record_ID LIKE \'2%\' || Record_ID LIKE \'9%\' 
          && Field_ID = \''. $metadata . '\');');
      
      $sth->execute;
      
      while (my @arr=$sth->fetchrow_array())
         {
         print @arr;
         }
      

      【讨论】:

        猜你喜欢
        • 2017-09-15
        • 2019-05-22
        • 2012-05-11
        • 1970-01-01
        • 2016-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多