选择与公司相关的所有用户

时间:2013-03-26 19:18:07

标签: sql select

首先,对于毫无意义的标题感到抱歉。想不出更好的事情。请看下面的表格:

用户

+-----+-------+---------------+
|  id | name  | email         |
+-----+-------+---------------+
|   1 | NameA | namea@srv.com |
|   2 | NameB | nameb@srv.com |
|   3 | NameC | namec@srv.com |
+-----+-------+---------------+

+-----+---------+-------+---------+
|  id | company | name  | manager |
+-----+---------+-------+---------+
|   1 |       1 | DeptA |       1 |
|   2 |       1 | DeptB |       2 |
+-----+---------+-------+---------+

公司

+-----+------+-------+
|  id | name | owner |
+-----+------+-------+
|   1 | Buzz |     3 |
+-----+-------+------+

我需要找到与公司相关的所有用户。类似的东西:

+---------+------------+
| user_id | company_id |
+---------+------------+
|       1 |          1 |
|       2 |          1 |
|       3 |          1 |
+---------+------------+

我该怎么做?我读到了不同类型的连接(内部,外部,完整等),但我无法弄清楚如何处理所有内容中的“部门”表。

3 个答案:

答案 0 :(得分:3)

我会用两个查询来做这件事:

select Department.manager as user_id, Company.id
from Company
join Department on Department.company=Company.id

union

select Company.owner as user_id, Company.id
from Company

答案 1 :(得分:0)

select User.id, User.name, User.email, CASE WHEN User.id = Company.Owner THEN 'YES' ELSE 'NO' END as CompanyOwner
from User
inner join Department on User.DepartmentID = Department.id
inner join Company on Company.id = Department.company

我认为您错过了用户和部门之间的实体关系,可能是用户表上的部门ID。我想这可能是你错过的部分。

答案 2 :(得分:0)

通常,您可以通过某种方式将用户链接到他们所在的部门。或者将DeptID列添加到User表中。在此示例中,所有者的部门表示为null,而管理员部门则填充,但您执行此操作的方式取决于您。

 User
+-----+-------+---------------+------+
|  id | name  | email         | dept |
+-----+-------+---------------+------+
|   1 | NameA | namea@srv.com |    1 |
|   2 | NameB | nameb@srv.com |    2 |
|   3 | NameC | namec@srv.com |  +++ |   
|   4 | NameD | named@srv.com |    2 |
|   5 | NameE | namee@srv.com |    2 |
+-----+-------+---------------+------+ 

因此,要获取在User表中填充部门的所有公司1用户的列表,这将变得简单

SELECT u.id       as user_id,
       d.company  as company_id
  FROM User u
  INNER JOIN Department d   ON u.dept=d.id
  WHERE d.company=1

UNION

SELECT owner  as user_id,
       id     as company_id
  FROM Company

如果您选择不在User表中填充经理的部门,那么您还必须为该部分添加UNION,类似于构造与上面的第一部分。

您可能会有一个关联表来显示哪些员工适用于哪个部门。如果一个人可以在多个部门工作,则可能需要这样做。 (经理和所有者可能不需要在这个表中,因为它们已经被考虑了。再次,由你决定。但如果你确实包含它们,那么你就不需要UNION了,所以它会让事情更简单。你可能会甚至把所有者放在“OWNERSHIP”部门。)

 UserDept
+--------+--------+
| UserID | DeptID |
+--------+--------+
|    4   |    2   |
|    5   |    2   |
+--------+--------+

SELECT u.id       as user_id,
       d.company  as company_id
  FROM UserDept u
  INNER JOIN Department d   ON u.dept=d.id
  WHERE d.company=1

(如果您未在UserDept表中包含所有者/经理,则根据需要添加UNION。)

但是如果您需要更深入的示例,我们假设您还需要User表中的名称:

SELECT u.id       as user_id,
       d.company  as company_id,
       u.name     as user_name
  FROM User u
  INNER JOIN UserDept x     ON u.id=x.user
  INNER JOIN Department d   ON x.dept=d.id
  WHERE d.company=1