我现在被困了好几天了。我不确定我的数据库设计效率低下还是我的查询错误。 关于绩效的最佳解决方案是什么?
我有如下表格:
View:
+--------+--------------+
+ idEmpl + idDepartment +
+--------+--------------+
+ 1 + 1 +
+ 2 + 1 +
+ 3 + 2 +
+--------+--------------+
# customer is a supplier for department of employee
Table supplier:
+--------+----------------+----------------+
+ idEmpl + idCustomer + nrSupplier +
+--------+----------------+----------------+
+ 1 + 2 + 0815 +
+ 1 + 4 + 0816 +
+ 2 + 5 + 0817 +
+ 3 + 4 + 4711 +
+--------+----------------+----------------+
# customer is a manufacturer for department of employee
Table manufacturer:
+--------+----------------+----------------+
+ idEmpl + idCustomer + nrManufacturer +
+--------+----------------+----------------+
+ 1 + 2 + a111 +
+ 2 + 5 + a113 +
+ 3 + 4 + b492 +
+--------+----------------+----------------+
Wanted result after query:
+--------+------------+------------+----------------+
+ idEmpl + idCustomer + nrSupplier + nrManufacturer +
+--------+------------+------------+----------------+
+ 1 + 2 + 0815 + a111 +
+ 1 + 4 + 0816 + NULL +
+ 2 + 5 + 0816 + a112 +
+--------+------------+------------+----------------+
由于idCustomer不是员工部门的现有制造商,因此应该为NULL但我最近的查询返回' b492'来自员工3和他的部门2。
如果我将idDepartment添加到表供应商和制造商,我认为没有问题。 但我认为不需要存储子ID,父ID。
两个查询都不会选择idDperatment = 1 ..
SELECT v.*, s.nrSupplier, m.nrManufacturer
FROM view v
LEFT JOIN supplier s ON (v.idEmpl=s.idEmpl AND v.idDepartment=1)
LEFT JOIN manufacturer m ON (v.idEmpl=m.idEmpl AND v.idDepartment=1);
这将仅返回员工,但不会返回整个部门,供应商/制造商可能会设置不同的员工。
SELECT v.*, s.nrSupplier, m.nrManufacturer
FROM view v
LEFT JOIN supplier s ON (v.idEmpl=s.idEmpl)
LEFT JOIN manufacturer m ON (v.idEmpl=m.idEmpl)
WHERE v.idDepartment=1;
即使您与idDepartement
无关,仍会选择第一个找到的nrSupplierSELECT v.*, s.nrSupplier, m.nrManufacturer
FROM view v
LEFT JOIN supplier s ON (v.idCustomer=s.idCustomer AND vcc.idDepartment=1)
LEFT JOIN manufacturer m ON (v.idCustomer=m.idCustomer AND vcc.idDepartment=1);
答案 0 :(得分:0)
加入manufacturer
和idEmpl
的{{1}}表格,以获得该结果:
idCustomer