请帮我写一个mysql查询来选择特定部门的成员

时间:2011-02-07 13:11:27

标签: mysql

假设我有2个表,employeedepartmentdepartment有2个部门,dpt1和dpt2,有12个员工,6个是每个部门,4个属于两个部门。如何使用mysql查询查找仅属于dpt2而非dpt1的员工?

2 个答案:

答案 0 :(得分:0)

SELECT employee.*
FROM employee
INNER JOIN employee_belongs_to_departments
WHERE employee.id = employee_belongs_to_departments.employee_id
AND employee_belongs_to_departments.department_id = 'dpt2'
AND employee.id NOT IN (
  SELECT DISTINCT ebtd2.employee_id
  FROM employee_belongs_to_departments ebtd2
  WHERE ebtd2.employee_id = employee.id
  AND ebtd2.department_id = 'dpt1'
)

答案 1 :(得分:0)

在这种情况下,通常的方法是建立第三个“连接”表,称为employeeDepartment

CREATE TABLE employeeDepartment (
    employee INT UNSIGNED NOT NULL,
    department INT UNSIGNED NOT NULL,
    PRIMARY KEY (employee, department)
)

然后你还可以为相应表的主键创建employeedepartment个外键,但这需要你使用正确的存储引擎(不是很难做到的)

这使得做各种事情比你想要的方法更容易(在一列中存储值列表)。

然后你可以使用

SELECT
    eD1.employee
FROM
    employeeDepartment AS eD1
    LEFT JOIN employeeDepartment AS eD2 ON
        eD1.employee = eD2.employee AND
        eD2.department = 'dpt2' -- replace with appropriate integer
                                -- if using integers as I suggested
WHERE
    eD1.department = 'dpt1' AND -- same comment applies
    eD2.employee IS NULL