I am importing a product list from an XML file. The supplier who built the XML file outputs every variation of a product, as a separate product. For example, a T-shirt which has three different sizes and three different colours, is listed in the XML files as 9 separate products, rather than 1 T-shirt with 9 options. I need to try link them together and the best way I can think of is to build a hierarchy.
This is how I have built it using PHP and MYSQL, but it takes forever to process. I’m 99.9999% certain that SQL could do this job directly in a few seconds. The problem is I don’t know to find the children and add them.
Any SQL experts here who can help with this?
// Add parent product into hierarchy
$stmt = "INSERT INTO ProductHierarchy (product_id, is_parent) SELECT product_id, 1 FROM ActiveProducts WHERE product_id NOT IN (SELECT product_id FROM ProductHierarchy) GROUP BY name";
$result = mysqli_query($sql_connect, $stmt);
// Get list of parents from hierarchy
$stmt = "SELECT ph.product_id, ap.name FROM ProductHierarchy ph INNER JOIN ActiveProducts ap ON ph.product_id = ap.product_id";
$result = mysqli_query($sql_connect, $stmt);
while ($row = mysqli_fetch_assoc($result)) {
// Add new child to parent
$substmt = "INSERT INTO ProductHierarchy (product_id, is_child, parent_id) SELECT product_id, 1, '" . $row['product_id'] . "' FROM ActiveProducts WHERE name = '" . $row['name'] . "' and product_id NOT IN (SELECT product_id FROM ProductHierarchy)";
$subresult = mysqli_query($sql_connect, $substmt);
}