2011-04-25 85 views
2

美好的一天MYSQL IN

我想查詢在每個項目上工作的員工的姓名。 我的代碼如下:

SELECT CONCAT (fname,' ', minit,'. ' , lname) AS NAME 
FROM employee a, works_on b, project c 
WHERE pno IN (Select pnumber  //WHAT COULD I SUBSTITUTE W/ IN 
       FROM projet) 
    AND a.ssn = b.essn 
    AND b.pno = c.pnumber 

在的問題是,它是價值觀裏面都像評價爲「OR」 ......是什麼的,使我的子查詢的評估值相當於like'AND'

謝謝您提前。

編輯: 作爲reqeusted ..

enter image description here

+0

我不明白。一列如何同時具有多個值? – 2011-04-25 14:53:31

+0

@Pekka有什麼建議嗎? – newbie 2011-04-25 14:57:01

+0

@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

回答

4
SELECT * 
FROM employee e 
WHERE NOT EXISTS 
     (
     SELECT NULL 
     FROM employee ei 
     CROSS JOIN 
       project p 
     LEFT JOIN 
       works_on wo 
     ON  wo.pno = p.pnumber 
       AND wo.essn = ei.ssn 
     WHERE ei.ssn = e.ssn 
     ) 
+0

我向你的SQL掌握鞠躬。太好了! – 2011-04-25 15:00:28

2
select CONCAT (fname,' ', minit,'. ' , lname) AS NAME 
from employee 
left join works_on 
on works_on.essn=employee.ssn 
group by employee.ssn 
having count(works_on.essn) = (select count(*) from project); 
1

簡化的例子:

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