I am trying to query a MySQL database through Perl. My database has a table whose primary key is
a composite of three columns PK1, PK2 and PK3. I have arrays arr1 and arr2 which contain some values
of PK1 and PK2 respectively. I want to find the corresponding value of PK3 in the database for every
possible combination of arr1 and arr2 (there may be some combinations for which there is no value
of PK3). For example:
PK1 PK2 PK3
"JIM" "RED" 1
"JOHN" "BLUE" 2
"ANN" "GREEN" 3
"ANN" "WHITE" 4
"ME" "BLACK" 5
"ME" "RED" 6
arr1 = ("JIM", "ME", "ANN")
arr2 = ("BLACK", "RED")
I should get the result:
arr3 = (1, 5, 6)
The best solution I could come up with was:
foreach my $el1 (@arr1) {
$i = 0;
$query = "SELECT PK3 FROM table WHERE PK1 = $el1 AND PK2 = ?;";
foreach my $el2 (@arr2) {
my $query_handle = $connxn->prepare($query);
$query_handle->execute($el2);
$query_handle->bind_columns(undef, \$rec);
while($query_handle->fetch()) {
push(@arr3, $rec);
}
}
}
But this won’t work because there will be combinations of $el1 and $el2 for which there will be
nothing to bind. Is there any better/ faster way of doing this? Its a big table and the arrays are
also long, so my program would take time even if it does not give me an error. I am out of ideas here,
so any help will be appreciated. Thanks!
The query you want is:
See it on sqlfiddle.
To construct it: