我有数据库,在其他表中我有一个:
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');
答案 0 :(得分:0)
还简单地包含pid <> pid(假设这是主键,从您的定义看来确实如此)
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
-- Add this to WHERE
AND p1.pid != p2.pid
答案 1 :(得分:0)
尝试
SELECT p1.name, p2.name
FROM Physiotherapist p1, Physiotherapist p2
WHERE p1.cid = p2.cid AND p1.name !=(SELECT p2.name) AND p1.pid > p2.pid
这样,您应该只从两种可能的组合中获得一种。
答案 2 :(得分:0)
我认为下面的查询将为您服务
select T3.* from
(select clname,count( distinct pname) from
(SELECT p1.name as pname,c.name as clname
FROM Physiotherapist p1 inner join
Clinic c on p1.cid=c.cid
) as T GROUP BY clname
having count( distinct pname)>1
) T2 inner join
(SELECT p1.name as pname,c.name as clname
FROM Physiotherapist p1 inner join
Clinic c on p1.cid=c.cid
) t3 on t2.clname=t3.clname
答案 3 :(得分:0)
为了给您一个主意,我有一个带有authorid和bookid字段的出版物表。要获得至少一本书的共同作者,我的sql查询是:
SELECT p1.authorid , p2.authorid
FROM publications p1 , publications p2
WHERE p1.bookid = p2.bookid AND p1.authorid<>p2.authorid AND p1.authorid>p2.authorid;
希望你明白了