Mysql: 多个自连接?
Mysql: Multiple Self Join?
我正在构建一个症状检查器。当用户选择症状时,我们会建议具有用户 select 共同症状的疾病的其他症状,直到我们可以缩小到特定疾病。我有这个 table.
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 |
+----+----------+-----------+
如果我想要 select ailment_ids 个具有 symptom_id 1 和 2 的条目,我使用这个自连接查询。
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'
这将 return
+----------+
|ailment_id|
+----------+
| 1 |
| 4 |
+----------+
超过两个symptom_id怎么办。我想编写一个 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 '....'
请帮我用合适的代码替换注释。
您也可以通过聚合来做到这一点。您可能更容易构造这样的查询,因为它更容易处理附加属性。
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
子句中列表中的元素数相匹配。然后它将概括为任意数量的症状。
我正在构建一个症状检查器。当用户选择症状时,我们会建议具有用户 select 共同症状的疾病的其他症状,直到我们可以缩小到特定疾病。我有这个 table.
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 |
+----+----------+-----------+
如果我想要 select ailment_ids 个具有 symptom_id 1 和 2 的条目,我使用这个自连接查询。
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'
这将 return
+----------+
|ailment_id|
+----------+
| 1 |
| 4 |
+----------+
超过两个symptom_id怎么办。我想编写一个 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 '....'
请帮我用合适的代码替换注释。
您也可以通过聚合来做到这一点。您可能更容易构造这样的查询,因为它更容易处理附加属性。
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
子句中列表中的元素数相匹配。然后它将概括为任意数量的症状。