我有一个数据库,其中除其他表之外,还有这个表:
CREATE TABLE `Physiotherapist`(
`pid` INT,
`name` VARCHAR(40),
`hours` INT,
`cid` INT
我想编写一个SQL查询,返回在同一诊所工作的物理治疗师对列表,但不会返回重复结果。到目前为止,我的答案是:
SELECT p1.name AS name1, p2.name AS name2
FROM Physiotherapist p1
INNER JOIN Physiotherapist p2 on p2.cid = p1.cid AND p1.name != p2.name
或者通过自连接实现替代解决方案:
SELECT p1.name, p2.name
FROM Physiotherapist p1, Physiotherapist p2
WHERE p1.cid = p2.cid AND p1.name !=(SELECT p2.name)
无论哪种方式,我都能得到这个结果:
name1: name2:
Jan Christensen Ira Assent
Ira Assent Jan Christensen
即,同一对数据。我只需要其中的一个副本,因为它们显示相同的信息,但我无法找到一种方便的方法来实现。
编辑:带有示例数据的完整数据库代码
DROP TABLE IF EXISTS Physiotherapist;
CREATE TABLE `Physiotherapist`(
`pid` INT,
`name` VARCHAR(40),
`hours` INT,
`cid` INT
);
INSERT INTO Physiotherapist VALUES('123','Ira Assent','8','1');
INSERT INTO Physiotherapist VALUES('246','Annika Schmidt','1','2');
INSERT INTO Physiotherapist VALUES('327','Jan Christensen','5','1');
INSERT INTO Physiotherapist(`pid`,`name`) VALUES('455','Simon Winter');
DROP TABLE IF EXISTS Clinic;
CREATE TABLE `Clinic`(
`cid` INT,
`name` VARCHAR(40),
`address` VARCHAR(40)
);
INSERT INTO Clinic VALUES ('1','PhysCentral','Aarhus C');
INSERT INTO Clinic VALUES ('2','PhysIOgnomy','Aarhus N');
INSERT INTO Clinic VALUES ('3','Physios','Aarhus V');
DROP TABLE IF EXISTS Appointment;
CREATE TABLE `Appointment`(
`aid` INT,
`date` DATE,
`time` INT,
`pid` INT
);
INSERT INTO Appointment VALUES(34716,'2018-06-12','10','246');
INSERT INTO Appointment VALUES(23118,'2018-08-18','11','327');
INSERT INTO Appointment VALUES(88223,'2018-10-03','9','246');