我在下面運行的代碼運行得非常好,直到我嘗試在最後一個循環中獲取數量。我認爲它可能可以通過JOINs等進行優化,但是在抓取DISTINCT元素時,我並不太熟悉最佳方法?SQL查詢運行超慢
$sql_dept = "SELECT DISTINCT `department_guid` FROM `bom_material_copy` WHERE `complex_guid`='9EB75BE9-26E2-AEBB-1B52-37DBC2FB89EA' ORDER BY `id` DESC LIMIT 0,5";
foreach($pdo->query($sql_dept) AS $dept)
{
$sql_mat = "SELECT DISTINCT `material_bct_number` FROM `bom_material_copy` WHERE
`complex_guid`='9EB75BE9-26E2-AEBB-1B52-37DBC2FB89EA' AND
`department_guid`='".$dept['department_guid']."'
ORDER BY `id` DESC LIMIT 0,5";
foreach($pdo->query($sql_mat) AS $mat)
{
echo "<tr>";
echo "<td>".$mat['material_bct_number']."</td>";
// Grab Units Again
$u = 0;
$sql_unit = "SELECT DISTINCT `unit_number` FROM `bom_projects_units` WHERE `complex_guid`='9EB75BE9-26E2-AEBB-1B52-37DBC2FB89EA'";
foreach($pdo->query($sql_unit) AS $unit)
{
$sql_quan = "SELECT `quantity` FROM `bom_material_copy`
WHERE
`material_bct_number`='".$mat['material_bct_number']."' AND
`unit_number`='".$unit['unit_number']."' AND
`department_guid`='".$dept['department_guid']."'";
foreach($pdo->query($sql_quan) AS $quan)
{
echo "<td>".$quan['quantity']."</td>";
}
}
echo "</tr>";
}
}
嵌套查詢在性能上很昂貴;嘗試通過使用JOIN減少查詢的數量 –
除了Mark的評論,它是一個大型數據庫嗎?您正在查詢的表是否正確編入索引? –
這是一個更大的數據庫是的。具有數量,ID列和QUANTITY列的表都是索引的,但僅此而已。 –