任务的定义:使用OR从两个不同的列中获取数据。
问题
:在与普通(MySQL)查询一起使用时,由于bind variables的数量不均,Perl DBI引发异常。让我们假设以下数据库模式:
运算符组合了对列[[vpn_primary_ip和vpn_secondary_ip的搜索。 plain SQL查询如下:customer vpn_primary_ip vpn_secondary_ip 1000 1.1.1.1 2.2.2.2 1001 3.3.3.3 NULL 1002 4.4.4.4 5.5.5.5 1003 NULL 6.6.6.6
旁注
:由于存储IP地址的列是不可预测的,因此我使用OR
SELECT
customer,
vpn_primary_ip,
vpn_secondary_ip,
FROM
table
WHERE
vpn_primary_ip IN ( '1.1.1.1', '4.4.4.4', '5.5.5.5', '6.6.6.6' )
OR
vpn_secondary_ip IN ( '1.1.1.1', '4.4.4.4', '5.5.5.5', '6.6.6.6' );
上面的查询给出以下(适当的)结果:
+----------+-----------------+------------------+ | customer | vpn_primary_ip | vpn_secondary_ip | +----------+-----------------+------------------+ | 1000 | 1.1.1.1 | 2.2.2.2 | | 1002 | 4.4.4.4 | 5.5.5.5 | | 1003 | NULL | 6.6.6.6 | +----------+-----------------+------------------+
与Perl DBI相同的SQL查询:
my @ip_addresses = ('1.1.1.1', '4.4.4.4', '5.5.5.5', '6.6.6.6'); my $sth = $dbh->prepare ( "SELECT customer, vpn_primary_ip, vpn_secondary_ip, FROM table WHERE vpn_primary_ip IN ( @{[join',', ('?') x @ip_addresses]} ) OR vpn_secondary_ip IN ( @{[join',', ('?') x @ip_addresses]} )" ); $sth->execute(@ip_addresses);
引发以下异常:
DBD::mysql::st execute failed: called with 4 bind variables when 8 are needed at get_vpn_customers line 211, <DATA> line 1. DBD::mysql::st execute failed: called with 4 bind variables when 8 are needed at get_vpn_customers line 211, <DATA> line 1.
使它起作用的唯一想法是将@ip_addresses传递给:execute
方法twice
$sth->execute(@ip_addresses, @ip_addresses);
或better实践?任务的定义:使用OR从两个不同的列中获取数据。问题:由于绑定变量数量不均,Perl DBI在使用普通(MySQL)查询时会引发异常。 ...问题
:这是正确的方法,还是还有另一种方法,例如best
$sth->execute(@ip_addresses, @ip_addresses);