我该如何解决员工和相关表的SQL查询

时间:2019-04-27 20:10:31

标签: mysql

create table EMPLOYEE (Fname varchar(15), Minit char, Lname varchar(15), Ssn int PRIMARY KEY, Bdate date, Address varchar(31), Sex char, Salary int, Super_ssn int, Dno int);

create table DEPENDENT (Essn int , Dependent_name varchar(15) , Sex char, Bdate date, Relationship varchar(15), PRIMARY KEY(Essn,Dependent_name));

计算属于每个男性雇员的每种性别的受抚养者人数。显示lname,ssn,受抚养人数量和受抚养人性别。按名称排序。

我的SQL查询如下:

CREATE VIEW R1 AS
SELECT Lname as 'LAST NAME', Ssn
FROM EMPLOYEE WHERE SEX='M';
SELECT * FROM R1;

SELECT * FROM R1
CROSS JOIN (
SELECT  Essn, Sex as 'SEX OF DEPENDENT', COUNT(Dependent_name) as 'COUNT OF DEPENDENTS'
    from DEPENDENT
    group by Essn, Sex
    order by Essn)TT
where R1.Ssn = Essn;

但是当我只想要一个时,这给了我2个ssn列。我该如何更改查询?

1 个答案:

答案 0 :(得分:0)

在这段代码中:

    SELECT * FROM R1 
    CROSS JOIN ( SELECT Essn, Sex as 'SEX OF DEPENDENT', COUNT(Dependent_name) as 'COUNT OF DEPENDENTS' 
    from DEPENDENT group by Essn, Sex order by Essn)TT 
    where R1.Ssn = Essn;

您已经从R1中选择了SSN(从R1中选择*)和从交叉联接TT中选择了Essn。如果只想看到一个,则只需选择一个。

尝试从R1中选择所有内容,然后从交叉联接TT中完全选择您想要的内容:

    SELECT R1.*,TT.`SEX OF DEPENDENT`, TT.`COUNT OF DEPENDENTS` 
    FROM R1 CROSS JOIN ( SELECT Essn, Sex as 'SEX OF DEPENDENT', COUNT(Dependent_name) as 'COUNT OF DEPENDENTS' 
    from DEPENDENT group by Essn, Sex order by Essn )TT 
    on R1.Ssn = Essn

还要考虑联接中的命名约定,这使得选择TT。SEX OF DEPENDENT而不是TT.Sex变得更加困难