在mysql中使用外连接来连接子表

时间:2013-07-01 00:23:22

标签: mysql sql outer-join

我有一个关于外连接的新手问题。我有5个具有以下结构的表。

employee (employee_id, name, address)
employee_benefits (employee_id, benefit_id, join_date)
insurance (insurance_id, name)
insurance_benefits (insurance_id, benefit_id)
benefit (benefit_id, title)

对于选定的员工,我需要选择所有保险,其福利与员工可享受的全部或部分福利相匹配。 例如:

benefit(
    bn1, 1st benefit;
    bn2, 2nd benefit;
    bn3, 3rd benefit;
    bn4, 4th benefit; 
)

employee(
    123, bill jones, 123 main st;
    321, alex baldwin, 222 state st;
)

employee_benefits(
    123, bn1;
    123, bn2;
    123, bn4; 
    321, bn3;
    321, bn4;
)

insurance(
    ins1, 1st insurance;
    ins2, 2nd insurance;
    ins3, 3rd insurance
)

insurance_benefits(
    ins1, bn1;
    ins1, bn2;
    ins2, bn1;
    ins2, bn3;
    ins2, bn4;
    ins3, bn2;
    ins3, bn4;
)

对于员工123.我需要选择所有保险,这些保险既有福利的完整列表,也包括员工持有的福利的一部分,但不包括雇员没有持有福利的实例。在上面的例子中,它将是ins1和ins3。

有没有办法使用外连接来完成上述操作?

1 个答案:

答案 0 :(得分:0)

您可以使用外连接执行此操作,但我认为使用IN - 子句与子查询更直观。

员工123未持有的好处:

SELECT benefit_id
  FROM benefit
 WHERE benefit_id NOT IN
        ( SELECT benefit_id
            FROM employee_benefits
           WHERE employee_id = 123
        )
;

提供上述任何优惠的保险计划:

SELECT DISTINCT insurance_id
  FROM insurance_benefits
 WHERE benefit_id NOT IN
        ( SELECT benefit_id
            FROM employee_benefits
           WHERE employee_id = 123
        )
;

不提供上述任何优惠的保险计划:

SELECT insurance_id
  FROM insurance
 WHERE insurance_id NOT IN
        ( SELECT DISTINCT insurance_id
            FROM insurance_benefits
           WHERE benefit_id NOT IN
                  ( SELECT benefit_id
                      FROM employee_benefits
                     WHERE employee_id = 123
                  )
        )
;