简体   繁体   English

如何在Perl的DBI中使用绑定查询选择空行?

[英]How can I select rows that are null using bound queries in Perl's DBI?

I want to be able to pass something into an SQL query to determine if I want to select only the ones where a certain column is null. 我希望能够将某些内容传递给SQL查询,以确定是否只选择某个列为null的那些查询。 If I was just building a query string instead of using bound variables, I'd do something like: 如果我只是构建一个查询字符串而不是使用绑定变量,我会做类似的事情:

if ($search_undeleted_only)
{
    $sqlString .= " AND deleted_on IS NULL";
}

but I want to use bound queries. 但我想使用绑定查询。 Would this be the best way? 这会是最好的方式吗?

my $stmt = $dbh->prepare(...
    "AND (? = 0 OR deleted_on IS NULL) ");
$stmt->execute($search_undeleted_only);

Yes; 是; a related trick is if you have X potential filters, some of them optional, is to have the template say " AND ( ?=-1 OR some_field = ? ) " , and create a special function that wraps the execute call and binds all the second ?s. 一个相关的技巧是,如果你有X个潜在过滤器,其中一些是可选的,是让模板说" AND ( ?=-1 OR some_field = ? ) " ,并创建一个包装执行调用并绑定所有的特殊函数秒? (in this case, -1 is a special value meaning 'ignore this filter'). (在这种情况下,-1是一个特殊值,意思是“忽略此过滤器”)。

Update from Paul Tomblin: I edited the answer to include a suggestion from the comments. Paul Tomblin的更新:我编辑了答案,包括评论中的建议。

So you're relying on short-circuiting semantics of boolean expressions to invoke your IS NULL condition? 那么你是否依赖于布尔表达式的短路语义来调用你的IS NULL条件? That seems to work. 这似乎有效。

One interesting point is that a constant expression like 1 = 0 that did not have parameters should be factored out by the query optimizer. 一个有趣的观点是,查询优化器应该考虑一个不具有参数的常量表达式,如1 = 0 In this case, since the optimizer doesn't know if the expression is a constant true or false until execute time, that means it can't factor it out. 在这种情况下,由于优化器在执行时间之前不知道表达式是否为常数truefalse ,这意味着它无法将其分解。 It must evaluate the expression for every row. 它必须评估每一行的表达式。

So one can assume this add a minor cost to the query, relative to what it would cost if you had used a non-parameterized constant expression. 因此,可以假设这为查询添加了较小的成本,相对于使用非参数化常量表达式所花费的成本。

Then combining with OR with the IS NULL expression may also have implications for the optimizer. 然后将ORIS NULL表达式结合使用也可能对优化器有影响。 It might decide it can't benefit from an index on deleted_on , whereas in a simpler expression it would have. 它可能决定它不能从deleted_on的索引中deleted_on ,而在一个更简单的表达式中它会有。 This depends on the RDBMS implementation you're using, and the distribution of values in your database. 这取决于您正在使用的RDBMS实现以及数据库中值的分布。

I think that's a reasonable approach. 我认为这是一种合理的方法。 It follows the normal filter pattern nicely and should give good performance. 它很好地遵循正常的过滤模式,应该提供良好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM