簡化的例子:
create table emp_work_on
(
emp_name varchar(50),
work_on varchar(30)
);
create table works
(
work_on varchar(30)
);
insert into works(work_on) values('apple'),('microsoft'),('google'),('facebook')
insert into emp_work_on values
('john','apple'),('john','microsoft'),('john','google'),('john','facebook'),
('paul','microsoft'),('paul','google'),
('george','apple'),('george','microsoft'),('george','google'),('george','facebook'),
('ringo','apple'),('ringo','facebook');
select e.emp_name
from works w
left join emp_work_on e on e.work_on = w.work_on
group by e.emp_name
having count(e.work_on) = (select count(*) from works)
order by e.emp_name
輸出:
emp_name
----------
george
john
(2 rows)
在你的表結構,你可以這樣做:
SELECT * FROM employee
WHERE ssn IN
(
SELECT w.essn
FROM project c
LEFT JOIN works_on w ON w.pno = c.pnumber
GROUP BY w.essn
HAVING COUNT(w.pno) = (SELECT COUNT(*) FROM project)
)
嗯..但我認爲這可能是最簡單的,給予有對員工的works_on沒有重複PNO,即有一個在works_on那並不是沒有PNO t存在於項目中,即保持參照完整性
SELECT * FROM employee
WHERE ssn IN
(
SELECT essn
FROM works_on
GROUP BY essn
HAVING COUNT(pno) = (SELECT COUNT(*) FROM project)
)
我不明白。一列如何同時具有多個值? – 2011-04-25 14:53:31
@Pekka有什麼建議嗎? – newbie 2011-04-25 14:57:01
@Pekka的含義是什麼,'IN('b','c')'等於WHERE a ='b'還是a ='c''。你想要的是'WHERE a ='b'AND a''c'',但是'a'既可以同時是'b'又可以'c''又怎麼樣? – Halcyon 2011-04-25 14:57:24