SELECT ssn, fname, lname
FROM employee A
WHERE { dependents of A where sex is opposite of A's sex } != ∅
SELECT ssn, fname, lname
FROM employee A
WHERE EXISTS
(SELECT essn
FROM dependent
WHERE essn = A.ssn
AND sex != A.sex
)
Suppose we wrote this query:
SELECT ssn, fname, lname
FROM employee
WHERE EXISTS
(SELECT essn
FROM dependent
WHERE essn = ssn // essn is dependent.essn, ssn is employee.ssn
AND sex != sex // Both sex attr's are: dependent.sex !!!
)
The association of attributes is as follows:
essn is dependent.essn because dependent is in inner scope (nearest)
ssn is employee.ssn (because dependent does not have ssn) !!!
sex is dependent.sex because dependent is in inner scope (nearest)
How to fix the query:
SELECT ssn, fname, lname
FROM employee
WHERE EXISTS
(SELECT essn
FROM dependent
WHERE essn = ssn /* (1) essn refers to dependent
(2) ssn refers to employee because
dependent has no "ssn" */
AND sex != employee.sex /* (1) sex (with no qualifier) refers to
dependent
(2) We must use employee.sex to refer to
the "sex" attr in the outer relation !!!
)
|