Mysql:多个自我加入?

时间:2015-01-25 18:30:57

标签: php mysql self-join

我正在构建症状检查程序。当用户选择症状时,我们建议患有其他症状的患者选择症状,直到我们可以缩小到特定疾病。我有这张桌子。

ailment_symptoms 
+----+----------+-----------+
|id  |ailment_id|symptom_id |
+----+----------+-----------+
|1   | 1        |  1        |
|2   | 1        |  2        |
|3   | 2        |  1        |
|4   | 2        |  3        |
|5   | 3        |  3        |
|6   | 3        |  2        |
|7   | 4        |  1        |
|8   | 4        |  2        |
+----+----------+-----------+

如果我想选择具有symptom_id 1和2的条目的ailment_id,我使用此自连接查询。

SELECT t1.ailment_id
FROM ailment_symptoms t1
JOIN ailment_symptoms t2 ON t1.ailment_id = t2.ailment_id
WHERE t1.symptom_id =  '1'
AND t2.symptom_id =  '2'

将返回

+----------+
|ailment_id|
+----------+
| 1        |
| 4        |
+----------+

当有两个以上的症状有效时,我该怎么办?我想写一个PHP代码,它将构建与用户输入的症状一样多的症状。代码应如下所示:

$user_symptoms = array($symptom_id_1, $symptom_id_2, $symptom_id_3);  //as many symptom as the user picks
$query = "SELECT t1.ailment_id FROM ailment_symptoms t1";

foreach($user_symptoms AS $symptoms){
      //here is where we construct the multiple self join and append it to $query
      //please replace this comment with appropriate code
 }

 $query .= "WHERE ";
 //loop through $user_symptoms and append t1.symptom_id =  '$user_symptom[0]' AND '....'

请帮我用适当的代码替换评论。

1 个答案:

答案 0 :(得分:5)

您也可以通过聚合执行此操作。您可能更容易构造这样的查询,因为它更容易处理其他属性。

SELECT s.ailment_id
FROM ailment_symptoms s
WHERE s.symptom_id in (1, 2)
GROUP BY s.ailment_id
HAVING COUNT(DISTINCT s.symptom_id) = 2;

你必须确保" 2"匹配where子句中列表中元素的数量。然后它会推广到任何数量的症状。