更好的选择从表中选择唯一数据

时间:2016-04-22 20:49:27

标签: sql database

我正在学习SQL。我想select employeeemp_name, emp_lname, project_name)只有一个project(不多或少)。

我在数据库中有3个表:

表:

create table employee(
    emp_id char (5) primary key,
    emp_name nvarchar(15) not null,
    emp_lname nvarchar(20)
);

create table project(
    pr_id char(5) primary key,
    project_name nvarchar(10) not null,
    project_budjet int
);

create table employee_project(
    emp_id char (5) foreign key references employee(emp_id),
    pr_id char(5) foreign key references project(pr_id),
    constraint premppk primary key(emp_id, pr_id)
);

我正在尝试select emp_id employee_project {/ 1}}。

此代码为emp_id

提供了唯一的employee_project
select emp_id, count(pr_id) from employee_project
    group by emp_id having count(pr_id) = 1

但我需要emp_idpr_idselect emp_nameemp_lnameproject_name。我也尝试select pr_id使用emp_id我已经拥有的内容。代码:

select ep.emp_id, ep.pr_id from employee_project as ep,
    (
    select emp_id, count(pr_id) from employee_project
        group by emp_id having count(pr_id) = 1
    ) CT
where CT.emp_id = ep.emp_id

现在我可以随心所欲地选择我需要的关于这些employeeproject的所有内容。最后代码:

select employee.emp_name, employee.emp_lname, project.project_name
    from employee, project, 
        (
        select ep.emp_id, ep.pr_id from employee_project as ep,
            (
            select emp_id, count(pr_id) from employee_project
                group by emp_id having count(pr_id) = 1
            ) CT
        where CT.emp_id = ep.emp_id
        ) CK
where CK.emp_id = employee.emp_id and CK.pr_id = project.pr_id

有没有办法轻松做到这一点。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

由于您只需要一个项目,因此您可以使用组中的任何聚合函数来获取项目。我使用了min(pr_id),但您也可以使用avg()max()

之后,您可以加入表格以获取所有其他列值。

select e.*, p.*
from 
(
  select emp_id, min(pr_id) as pr_id
  from employee_project
  group by emp_id 
  having count(pr_id) = 1
) ep
join employee e on e.emp_id = ep.emp_id
join project p on p.pr_id = ep.pr_id