2014-03-26 101 views
3

我的表是:如何在mysql中选择具有相同值的列?

patients(pid,name,city) 

disease(did,dname) 

has_disease(did,pid) 

我想列出谁拥有相同的一组diseases.pid并没有分别是在患者和疾病表的主键,并且在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,因为他们有exactl Ÿ同一套疾病1和3即疟疾和病毒性发烧。我想知道如何在mysql中实现这一点。我尝试了关系分区,但是它不起作用。

回答

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组患者通过他们的分布式入侵检测系统的完整列表,并留下使用相同的DID列表的PID,但不同的PID

相关问题