I have a database of dogs. Each dog has a sire and dam parent. I am not able to use CTE for this due to an issue with phpmyadmin and MariaDB 10.0.
Table is animal
Columns I am working with are:
id
, akc_reg_num
, akc_parent_sire
, akc_parent_dam
I have tried to get just one generation as I would for loading subcategories, but this is only one side when there are two parents.
I have attempted this solution, but can't get my head wrapped around the two parents of each sibling. How do I select only one generation of a hierarchical tree using an table parent child relation with SQL?
Example Table
CREATE TABLE `animal` (
`id` INT(11) NOT NULL AUTO_INCREMENT ,
`akc_reg_num` VARCHAR(20) NOT NULL ,
`akc_parent_sire` VARCHAR(20) NOT NULL ,
`akc_parent_dam` VARCHAR(20) NOT NULL ,
PRIMARY KEY (`id`)
) ENGINE = MyISAM;
INSERT INTO `animal` (`id`, `akc_reg_num`, `akc_parent_sire`, `akc_parent_dam`) VALUES
(NULL, '1', '2', '3'),
(NULL, '2', '5', '6'),
(NULL, '3', '9', ''),
(NULL, '5', '', ''),
(NULL, '6', '7', '8'),
(NULL, '7', '', ''),
(NULL, '8', '', ''),
(NULL, '9', '10', '11'),
(NULL, '10', '', ''),
(NULL, '11', '12', ''),
(NULL, '12', '', '');
Code:
include_once("db_conx.php");
function getPedigree($node) {
// look up the parent of this node
$sql = 'SELECT akc_parent_sire, akc_parent_dam FROM animals WHERE akc_reg_num="'.$node.'";';
$query = $db->prepare($sql);
$query->execute();
$path = array();
while($row=$query->fetch(PDO::FETCH_ASSOC)){
if ($row['akc_parent_sire']!='') {
$path[] = $row['akc_parent_sire'];
echo $row['akc_parent_sire'];
$path = array_merge(getPedigree($row['akc_parent_sire']), $path);
}
if ($row['akc_parent_dam']!='') {
$path[] = $row['akc_parent_dam'];
echo $row['akc_parent_dam'];
$path = array_merge(getPedigree($row['akc_parent_dam']), $path);
}
}
return $path;
}
print_r(getPedigree('vvv'));
I need to loop through each generation so I can return a json array and then use javascript to tie the results to DOM elements. I only need to query for 4 generations however my concern is the expense of cpu cycles. Once I have a few hundred thousand animals in the database how efficient will this same query be?