我正在渲染一個基於來自SQLite中的多個數據庫表的數據。如何改進這個SQL查詢(SQLite和PHP)
表:
- 人員 - 包含所有用戶/工作人員,可以有證書
- 證書---包含所有可用證書,用戶可以有
- rel__staff_certificate ---包含連接證書(關係)給用戶
TABLE staff
`staff_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
表certificates
`cert_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`caption` TEXT NOT NULL,
`description` TEXT
表rel__staff_certificate
`rel_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`staff_id` INTEGER,
`cert_id` INTEGER,
`cert_date` TEXT NOT NULL,
`comments` TEXT
。
。
因此,這裏的交易:
// Get all available certificates
$sql_get_cert = "SELECT * FROM certificates ORDER BY cert_id ASC";
// Get all certificates for staff user
$sql_get_staff_cert_rel = "SELECT * FROM rel__staff_certificate WHERE staff_id = :staff_id AND cert_id = :cert_id LIMIT 1";
// Prepare SQL queries...
$get_cert_rel = $PDODB->prepare($sql_get_staff_cert_rel);
$get_cert = $PDODB->prepare($sql_get_cert);
// Get all certificates to array $certdata
$get_cert->execute();
$certdata = $get_cert->fetchAll();
// Create the array where I want to push data to:
$staffdata[$i] = array(
$staff['staff_id'], // $staff() is populated earlier and works just fine
$staff['name'],
$ccdata['region'], // $ccdata() is populated earlier and works just fine
$ccdata['cc_code']
);
// Loop through all available certificates in table ´certificates´
foreach ($certdata as $cert) {
// Bind values for the relation SQL now when we have them all
$get_cert_rel->bindValue(':staff_id', $staff['staff_id']);
$get_cert_rel->bindValue(':cert_id', $cert['cert_id']);
$get_cert_rel->execute();
// Get the certification relation data to array $certreldata()
$certreldata = $get_cert_rel->fetch();
// If a certificate date exists, then use that for our array which tells us that this staff has this certificate and was certified on this date
if (!empty($certreldata['cert_date'])) {
array_push($staffdata[$i], $certreldata['cert_date']);
}
// If no certificate date exsits, then just add value "N/A" as not available
else {
array_push($staffdata[$i], 'N/A');
}
}
確定這樣完蛋了!它可以工作,但正如你所看到的,我正在向foreach()循環中的SQL服務器執行大量的SQL執行操作,我不相信這會很好,因爲它會消耗大量不必要的時間。
任何人都可以告訴我如何使用單個SQL查詢來做到這一點嗎?或者告訴我如何改進代碼,以其他方式進一步加快速度?
謝謝。
如何使用連接? –