有人知道一个声明,它会从输出中删除这样的重复项吗?
DEPARTMENT_ID DEPARTMENT_NAME FULL_NAME JOB_TITLE
50 Shipping Alana Walsh Sales Representative
50 Shipping Alana Walsh Sales Representative
50 Shipping Winston Taylor Sales Manager
50 Shipping Winston Taylor Sales Manager
60 IT Alexander Hunold Sales Representative
60 IT Alexander Hunold Sales Representative
这是我到目前为止所拥有的:
select employees.department_id, departments.department_name, first_name || ' ' || last_name as full_name, job_title
from departments, employees, jobs
where employees.department_id = departments.department_id
and job_title like '%Sales%'
order by job_title, full_name;
答案 0 :(得分:2)
您可以使用SELECT DISTINCT
删除重复项。
select distinct employees.department_id, departments.department_name, first_name || ' ' || last_name as full_name, job_title
from departments, employees, jobs
where employees.department_id = departments.department_id
and job_title like '%Sales%'
order by job_title, full_name;
或者,您也可以在每列上使用GROUP BY
select employees.department_id, departments.department_name, first_name || ' ' || last_name as full_name, job_title
from departments, employees, jobs
where employees.department_id = departments.department_id
and job_title like '%Sales%'
group by employees.department_id, departments.department_name, first_name || ' ' || last_name as full_name, job_title
order by job_title, full_name;
看起来你错过了一份工作联盟?这可能是您的查询返回重复结果的原因。
我还建议你尽可能使用显式连接语法。
FROM departments
INNER JOIN employees ON employees.department_id = departments.department_id
答案 1 :(得分:0)
您可以使用DISTINCT
作为Matt Busche指示。
然而,在许多情况下,人们错误地添加DISTINCT
来掩盖他们缺少连接条件这一事实。在您的情况下,您将一起加入三个表 - departments
,employees
和jobs
- 但您只有一个连接条件。因此,您正在与jobs
表进行笛卡尔联接,这几乎肯定不是您想要的。 jobs
表如何与其他两个表相关联?如果我们假设job_id
和jobs
表中都有employees
,那么您需要类似
select employees.department_id,
departments.department_name,
first_name || ' ' || last_name as full_name,
job_title
from departments, employees, jobs
where employees.department_id = departments.department_id
and jobs.job_id = employees.job_id
and job_title like '%Sales%'
order by job_title, full_name;