3

我有一些桌子:

员工:id、姓名、id_suc、id dep、id_sec
成功:id_suc,名称
部门:id_dep,id_suc,名称
秒:id_sec、id_dep、id_suc、名称

不要怪我,这是一个现有的应用程序,我没有创建数据库并且无法触及结构,因为里面有太多的数据和依赖它的报告。我只是想按要求修改报告。

我做一个查询:

SELECT DISTINCT 
  s.name as sucurs, 
  d.name as depart, 
  c.name as section, 
  e.name AS emp 
FROM 
  employee e 
  join suc s on (e.id_suc = s.id_suc) 
  join dep d on (e.id_dep = d.id_dep) 
  join sec c on (e.id_sec = c.id_sec) 
ORDER BY 
  sucurs, depart, section, emp

并给我带来了笛卡尔积。我想:

sucurs1, depart1, section1, emp1
sucurs1, depart1, section1, emp2
.....

(然后在我按 suc、dep、sec 分组的报告上)

相反,我得到了:

sucurs1, depart1, section1, emp1
sucurs2, depart1, section1, emp1

等等。它带来了 ALL sucurs、ALL depart、ALLsection和有时重复emp

我错过了一些东西,但不知道是什么。有什么线索吗?

4

1 回答 1

5

好吧,你总是只加入表employee- 似乎Dep也链接到- 所以你需要第二个 JOIN 条件(不仅加入,而且加入!)。表甚至需要三个JOIN 条件,因为它与表共享三个 id。Sucid_depid_sucSecEmployee

SELECT DISTINCT 
  s.name as sucurs, 
  d.name as depart, 
  c.name as section, 
  e.name AS emp 
FROM 
  employee e 
INNER JOIN 
  suc s ON e.id_suc = s.id_suc
INNER JOIN 
  dep d ON e.id_dep = d.id_dep AND e.id_suc = d.id_suc
INNER JOIN 
  sec c ON e.id_sec = c.id_sec AND e.id_suc = c.id_suc AND e.id_dep = c.id_dep
ORDER BY 
  sucurs, depart, section, emp
于 2012-03-26T13:03:47.683 回答