关于SQL查询的问题

时间:2011-06-29 15:35:56

标签: mysql sql join

我在MySQL DB中有三个表

表1包含以下字段

Name of Table: SupervisorTable 
supervisorid (autoinc, bigint) 
employeeid (bigint) //same as User.userid
supervisorname

Name of Table: User 
userid (autoinc, bigint) 
userFullName (string) 
supervisorid (bigint) 
divisionid (bigint)

Name of Table: DivisionTable 
divisionid(autoinc, bigint) 
divisionname (string)

我希望能够确定主管在哪个部门工作,我的输出应该是 主管姓名和部门名称。我的最新尝试:

SELECT supervisortable.supervisorname,
       divisiontable.divisionname 
  FROM supervisortable, 
       user, 
       divisiontable 
 WHERE supervisortable.employeeid = user.userid;

这给了每个部门的主管姓名的每个组合:

supervisorname  divisionname
----------------------------
UserA           Department1
UserB           Department1
UserA           Department2
...
UserB           DepartmentN

3 个答案:

答案 0 :(得分:3)

如果您想查找查找所有主管的查询并在OP中列出所需的输出,那么这样做:

SELECT S.supervisorname,
       D.divisionname
  FROM SuperisorTable S
  JOIN User U ON S.employeeid= U.supervisorid
  JOIN DivisionTable D ON U.divisionid = D.divisionid

因为没有标准,你会得到一个笛卡尔积(这很糟糕,除非你真的想要那个)。

答案 1 :(得分:0)

SELECT s.supervisorname, d.divisionname
FROM DivisionTable d, SupervisorTable s, User u
WHERE d.divisionid =  u.divisionid
AND s.supervisorid = u.supervisorid
AND s.employeeid = u.userid

答案 2 :(得分:0)

我正确理解您的数据结构:

SELECT 
  S.supervisorname,        
  D.divisionname 
FROM SuperisorTable S  
INNER JOIN Users U ON S.employeeid = U.userid  
INNER JOIN DivisionTable D ON U.divisionid = D.divisionid