我的表是:
patients(pid,name,city)
disease(did,dname)
has_disease(did,pid)
我想列出患有相同疾病的患者.pid和did分别是患者和疾病表中的主键,并且是has_disease表中的外键。
示例数据:
患者
pid name city
1 John X
2 Jim Y
3 Jack Z
疾病
did dname
1 Typhoid
2 Malaria
3 ViralFever
has_disease
did pid
1 1
1 2
3 2
1 3
3 3
上述数据的答案是Jim and Jack
,因为他们有完全相同的疾病1和3,即疟疾和病毒性发烧。我想知道如何在mysql中实现这一点。我尝试了关系师与哪里不存在,但它不起作用。
答案 0 :(得分:3)
select p.*, GROUP_CONCAT(d.did SEPARATOR ', ') AS all_dids
from patients p
JOIN has_disease hd ON p.pid=hd.pid
JOIN disease d ON d.did=hd.did
GROUP BY p.pid;
查询会让我们回答患者及其疾病。
SELECT *
FROM
(select p.*, GROUP_CONCAT(d.did SEPARATOR ', ') AS all_dids
from patients p
JOIN has_disease hd ON p.pid=hd.pid
JOIN disease d ON d.did=hd.did
GROUP BY p.pid) P1
JOIN
(select p.*, GROUP_CONCAT(d.did SEPARATOR ', ') AS all_dids
from patients p
JOIN has_disease hd ON p.pid=hd.pid
JOIN disease d ON d.did=hd.did
GROUP BY p.pid) P2 ON p1.all_dids=p2.all_dids and p1.pid<>p2.pid
比较2组患者的完整残疾名单,并将pid列表与相同的dids列表但不同的pid进行比较