SQL 中围绕查询的中期解决方案

midterm solution around query in SQL

这是数据库:

EMPLOYEE (fmane, minit, lname, ssn, birthdate, address, sex, salary, superssn, dno)     KEY: ssn
DEPARTMENT (dname, dnumber, mgrssn, mgrstartdate)               KEY: dnumber.
PROJECT  (pname, pnumber, plocation, dnum)                          KEY: pnumber.
WORKS_ON (essn, pno, hours)                                         KEY: (essn, pno)
DEPENDENT  (essn, dependent-name, sex, bdate, relationship)             KEY: (essn, dependent-name)

问的问题是...

Give the last name and SSN of the unmarried employees who work on two or more projects.

SELECT e.Lname, e.ssn
FROM Employee AS e
WHERE e.ssn IN (
        SELECT w.essn
        FROM works_on w
        GROUP BY w.essn
        HAVING count(*) >= 2
        )
    AND e.ssn NOT IN (
        SELECT essn
        FROM dependent
        WHERE relationship = 'Spouse'
        );

我的回答是错误的,因为我没有使用 e.ssn NOT IN 子句。

我的问题是:

1) group by 有什么用?仅适用于作品?

2)关于FROM Employee AS eAS是拼写错误还是命令?

3) having是包含吗?可以用其他命令代替吗?

1) 是的。 group by出现在sub-select

(
    select  w.essn
    from   works_on w
    group by w.essn
    having count(*) >= 2
)

并且只在那里有效。

2) "as" 创建一个别名,在本例中是 "e" 为 "employee"。这可以让你避免到处写员工的乏味。一些 SQL 数据库不需要 "as" 但这通常是个好主意,因为它使您的意图明确。

3) "Having" 就像一个 "Where" 对组中的每个成员进行操作。 https://en.wikipedia.org/wiki/Having_%28SQL%29