简体   繁体   中英

using outer join in mysql to join child tables

I have a newbie question about outer joins. I have 5 tables with the following structure.

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)

For a selected employee, I need to select all insurances with benefits matching either the full or partial set of benefits available to employees. Example:

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;
)

for employee 123. I need to select all insurances that have either the full list of benefits or a subset of the benefits held by the employee but not include instances that have benefits not held by the employee. in the above example, it would be ins1, and ins3.

is there a way to use outer join to accomplish the above?

You can do this with outer joins, but I think it's more intuitive to use IN -clauses with subqueries.

Benefits not held by employee 123 :

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

Insurance plans that offer any of the above benefits:

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

Insurance plans that don't offer any of the above benefits:

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
                  )
        )
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM