如何在mysql中删除非重复行?

时间:2014-02-25 01:17:01

标签: mysql

我正在尝试为拥有多个依赖项的所有员工显示ssn,名字(fname),姓氏(lname),依赖名称,依赖性和依赖关系。 我能够获得所有dependents的列表。什么是显示具有多个依赖项的条目的查询?

SHOW CREATE TABLE EMPLOYEE

Employee | CREATE TABLE `employee` (
`fname` varchar(15) NOT NULL,
`minit` varchar(1) DEFAULT NULL,
`lname` varchar(15) NOT NULL,
`ssn` char(9) NOT NULL DEFAULT '',
`bdate` date DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`salary` decimal(10,2) DEFAULT NULL,
`superssn` char(9) DEFAULT NULL,
`dno` int(11) DEFAULT NULL,
PRIMARY KEY (`ssn`),
KEY `fk_employee_department` (`dno`),
KEY `fk_employee_employee` (`superssn`),
CONSTRAINT `fk_employee_department` 
           FOREIGN KEY (`dno`) REFERENCES `department` (`dnumber`),
CONSTRAINT `fk_employee_employee` 
           FOREIGN KEY (`superssn`) REFERENCES `employee` (`ssn`)
ENGINE=InnoDB DEFAULT CHARSET=latin1 |

显示创建表依赖

    DEPENDENT | CREATE TABLE `dependent` (
 `essn` char(9) NOT NULL DEFAULT '',
 `dependent_name` varchar(15) NOT NULL DEFAULT '',
 `sex` char(1) DEFAULT NULL,
 `bdate` date DEFAULT NULL,
 `relationship` varchar(8) DEFAULT NULL,
 PRIMARY KEY (`essn`,`dependent_name`),
 CONSTRAINT `fk_dependent_employee` 
             FOREIGN KEY (`essn`) REFERENCES `employee` (`ssn`)
 ENGINE=InnoDB DEFAULT CHARSET=latin1 |

目前正在使用查询:

select e. ssn,e.fname,e.lname,d.dependent_name,d.sex,d.relationship 
from dependent AS d ,Employee as e
WHERE e.ssn=d.essn

1 个答案:

答案 0 :(得分:2)

使用子查询计算每个子查询的从属数量并将其加入。这将获得所需的过滤器:

select e.ssn, e.fname, e.lname, d.dependent_name, d.sex, d.relationship 
from Employee e join
     dependent d 
     on e.ssn = d.essn join
     (select d.essn, count(*) as cnt
      from dependent d
      group by d.essn
      having cnt >= 2
     ) d2
     on e.ssn = d2.essn
order by e.ssn;