由于我是初学者,我需要知道一件事。 我在这样的php中有一个查询..这个查询的最佳性能实现是什么:
select Sub_Code,Sub_Name from subj_mast where Dept_id=
(select Dep_Id from academic where Reg_No=$reg)
and Sem='$sem' and (Sub_Type='core' or subj_mast.Sub_Code=
(select Elective_code from elective where Reg_No=$reg and Sem='$sem'))
or subj_mast.Sub_Code
(select Sub_Code from history_of_arrear where Reg_No=$reg)
实际上这个查询运行良好,但我认为这会使检索变慢.. 帮助我...
答案 0 :(得分:1)
好的,经过一些重新安排后,我尽可能地清理并构建了SQL,我得到了这个:
SELECT
Sub_Code,
Sub_Name
FROM subj_mast
WHERE
Dept_id = (
SELECT
Dep_Id
FROM academic
WHERE
Reg_No=$reg
)
AND
Sem='$sem'
AND (
Sub_Type='core'
OR
subj_mast.Sub_Code=(
SELECT
Elective_code
FROM elective
WHERE
Reg_No=$reg
AND
Sem='$sem'
)
)
OR
subj_mast.Sub_Code = (
SELECT
Sub_Code
FROM history_of_arrear
WHERE
Reg_No=$reg
)
将子查询移动到连接中,并尽可能地优化它们,而无需访问数据库和数据的测试副本,这就是我想出的:
SELECT
S.Sub_Code,
S.Sub_Name
FROM subj_mast S
LEFT JOIN academic A
ON A.Dep_id = S.Dept_Id
LEFT JOIN history_of_arrear H
ON H.Sub_Code = S.Sub_Code
AND
H.Reg_No=A.Reg_No
LEFT JOIN Elective_code E
ON E.Sub_Code = S.Sub_Code
AND
E.Reg_No=$reg
AND
E.Sem='$sem'
WHERE
S.Sem='$sem'
AND
A.Reg_No=$reg
AND (
S.Sub_Type='core'
OR
E.Sub_Code IS NOT NULL
)
OR
H.Sub_Code IS NOT NULL
您应该创建以下索引:
CREATE INDEX idx_subjMas_dept_sem ON subj_mast(Dept_Id, Sem);
CREATE INDEX idx_academic_dep_regNo ON academic(Dep_id, Reg_No);
CREATE INDEX idx_historyOfArrear_subCode_regNo ON history_of_arrear(Sub_Code, Reg_No);
CREATE INDEX idx_ElectiveCode_sem_subCode_regNo ON history_of_arrear(Sem, Sub_Code, Reg_No);
哪个应该有助于MySQL进行这些连接。