0

员工可以在多个部门工作,每个部门可以有多个员工。因此需要一个关系表

表:
EMP(eid、ename、eage、esalary)
作品(eid、did、pct_time)
部门(did、dname、预算、managerid)

查找所有从事软件和硬件工作的员工:

SELECT e.ename FROM EMP e, Works w, Dept d 
WHERE e.eid = w.eid AND w.did = d.did AND d.did = 
(SELECT did FROM dept WHERE dname = 'Hardware' OR 'Software')  

根据乔恩:

SELECT e.ename FROM EMP e OR Works w OR Dept d 
WHERE e.eid = w.eid AND w.did = d.did AND d.did = 
(SELECT did FROM dept WHERE dname = 'Hardware' OR 'Software')

而且我只是不知道如何确保在同一 eid 下的硬件和软件在 Works 中有两个条目。

4

3 回答 3

1

Here's an alternative formulation of the query:

SELECT e.*
  FROM emp AS e
  JOIN (SELECT w.eid
          FROM works AS w JOIN dept AS d
            ON d.did = w.did AND d.dname = 'Software') AS s
    ON s.eid = e.eid
  JOIN (SELECT w.eid
          FROM works AS w JOIN dept AS d
            ON d.did = w.did AND d.dname = 'Hardware') AS h
    ON h.eid = e.eid

This has two symmetric sub-queries, one generating the employee IDs for the Software department, one generating employee IDs for the Hardware department. The selected employees are those whose ID is listed in both departments (because they're all inner joins).

于 2012-07-25T03:32:29.423 回答
1
select e.name
  from emp e, works h_w, dept h_d, works s_w, dept s_d
 where e.eid = h_w.eid
   and e.eid = s_w.eid
   and h_w.did = h_d.did
   and h_d.dname = 'Hardware'
   and s_w.did = s_d.did
   and s_d.dname = 'Software'
于 2012-07-25T03:06:24.017 回答
1

以下是有关如何解决该问题的步骤:

  • works首先,获取部门为硬件或软件的表中所有行
  • 然后,对于任何员工,如果存在两行,则意味着他/她在两个部门都工作。
  • 对于任何员工,如果存在少于两行,则意味着他/她只为两者之一工作,或者根本没有。
  • 我们需要检索正好有两行的员工。

所以我们首先可以做的是从works表中选择,将它与表连接起来dept,并过滤掉任何非硬件或软件的部门:

SELECT a.*
FROM works a
INNER JOIN dept b ON a.did = b.did
WHERE b.dname IN ('Hardware','Software')

然后我们要做的是按每个员工分组,这将使我们能够访问汇总信息,例如每个员工的行数,或 sum/max/min/avg/etc。的其他列。我们必须使用计数:

SELECT a.eid
FROM works a
INNER JOIN dept b ON a.did = b.did
WHERE b.dname IN ('Hardware','Software')
GROUP BY a.eid
HAVING COUNT(1) = 2

这只给了我们eid恰好有两行的 s(即适用于软件和硬件部门)。

eids还不够。我们想要有关员工的全部信息,因此我们必须包装整个查询并将其与员工表连接以获取其余信息:

SELECT a.*
FROM emp a
INNER JOIN 
(
    SELECT a.eid
    FROM works a
    INNER JOIN dept b ON a.did = b.did
    WHERE b.dname IN ('Hardware','Software')
    GROUP BY a.eid
    HAVING COUNT(1) = 2
) b ON a.eid = b.eid

你有它:在软件和硬件部门工作的员工。您可以单独执行上述每个查询,以查看我们如何得出最终解决方案的中间步骤。

于 2012-07-25T03:08:05.680 回答