MySQL查询留下了加入搞乱的事情

时间:2017-09-27 18:11:12

标签: mysql join left-join

此查询返回4行:

SELECT count(*) from 
patients join patient_observations on patients.patient_id=patient_observations.patient_id
join studies on patient_observations.study_id=studies.study_id AND studies.patient_id=patients.patient_id
join series on series.study_id=studies.study_id 
join instances on instances.series_id=series.series_id
join sop_classes on sop_classes.sop_class_id=instances.sop_class_id
join files on files.instance_id=instances.instance_id
join modalities on modalities.modality_id=series.modality_id
AND patient_name LIKE 'DRAGON^DEBBIE%';

如果我添加这个额外的行,它会返回3923行,这是错误的:

left join issuers on patients.issuer_of_patient_identifier=issuers.issuer_id

错误的是,发行人表只有121行:

mysql> select count(*) from issuers;
+----------+
| count(*) |
+----------+
|      121 |
+----------+
1 row in set (0.00 sec)

添加左连接的目的是,可能会有一些患者patients.issuer_of_patient_identifierNULL,好像我只是进行正常连接,它返回0行(请参阅:MySQL Matching where clause with optional NULL

请帮助,以便我可以获得正确的行(仅4)

1 个答案:

答案 0 :(得分:1)

A
------
1 a1
2 a2

B
-------
1 b1 a1
2 b2 a1



left join A and B
----------------------

1 a1 1 b1 a1
1 a1 2 b2 a1
2 a2 null null null
2 a2 null null null

这里有4行符合预期,如果算上(*),你将获得4行。但是如果你想知道表B中匹配的行数,你应该做count(distinct b.id)

摘要: 尝试count(distinct issuer.issuer_id)而不是count(*)

在聊天讨论后:

实际上,最大的问题是过滤条款。 sql应该如下 -

SELECT count(*) from 
patients join patient_observations on patients.patient_id=patient_observations.patient_id 
join studies on patient_observations.study_id=studies.study_id AND studies.patient_id=patients.patient_id 
join series on series.study_id=studies.study_id 
join instances on instances.series_id=series.series_id 
join sop_classes on sop_classes.sop_class_id=instances.sop_class_id 
join files on files.instance_id=instances.instance_id 
left join modalities on modalities.modality_id=series.modality_id 
left join issuers on (patients.issuer_of_patient_identifier=issuers.issuer_id) 
where patient_name LIKE 'DRAGON^DEBBIE%';