【发布时间】:2015-08-17 23:37:41
【问题描述】:
我有一个名为 Medicine 的表和一个名为 Medication_symptoms 的关联子表
医药
MediId, Name
1, MedA
2, MedB
3, MedC
药物治疗症状
MedSympId, Medicine (MedId), Symptom (symptomId)
1, MedA (1), Symptom A (1)
2, MedA (1), Symptom B (2)
3, MedB (2), Symptom B (2)
4, MedB (2), Symptom C (3)
5, MedC (3), Symptom D
我有另一个名为 Patient 和 Patient_Symptoms 的表
患者
PatientId, Name
1, Patient A
2, Patient B
3, Patient C
4, Patient D
Patient_Symptom
PatientSymptomId, PatientId, SymptomId
1, Patient A(1), Symptom A (1)
2, Patient A(1), Symptom B (2)
3, Patient B(2), Symptom B (2)
4, Patient B(2), Symptom D (4)
5, Patient D(4), Symptom D (4)
鉴于上述信息,我需要获得与患者所有症状相匹配的药物:(我会逐个提取每个患者的信息)
Patient A - Med A (as he has symptom a and b and Med is for symptom A and B)
Patient B - None! (as he has symptoms b and d and there is no medicine for symptoms B and D)
Patient D - Med C (as med C is for symptom D only and Patient D has only symptom D)
注意症状是一个单独的表格:
症状
Symptom Id, Name
1, Symptom A
2, Symptom B
3, Symptom C
4, Symptom D
5, Symptom E
这样的查询叫什么?
注意:我已经编造了这个例子。在我正在做的事情中,我有一个记录 A,带有一组属性(其中属性存储为记录 A 的记录行)。我需要将该记录 A 与另一条记录 C 匹配,该记录 C 具有与 A 完全相同的一组属性。(有意义吗?)
您可以使用http://pastebin.com/kaqdtHf3 处的脚本创建表格和一些示例数据
【问题讨论】:
-
请在您的示例数据中包含列名。
-
您介意解释一下您如何为患者确定药物的逻辑吗?例如,我看不到
Patient B是如何产生None!的。 -
匹配是否必须 100% 准确?例如,如果患者
X有症状A和B。并且药物Y是针对症状A、B和C定义的,药物Y是否应该退回? -
这样的查询叫什么? 就关系代数而言,您要寻找的是除法(您将患者的症状集与药物治疗的症状以获得可以治疗所有症状的药物)。 Celko 有一篇关于这个主题的好文章,有一些不同的解决方案:Divided We Stand: The SQL of Relational Division
-
@jpw,关于关系划分的文章 - 太棒了!谢谢!
标签: sql sql-server