我在mysql中有两个表,一个是student,另一个是student_sibling,其结构如下。
Student:
student_id name
------------------
1 anu
2 manu
3 tanu
4 pinu
.. ..
student_sibling 表:
student_id sibling_student_id
--------------------------------
1 4
15 4
2 1
6 15
如果我将 id 1 的兄弟插入为 4,则语音也是兄弟,同样,1 也是 15 和 2 的兄弟 例如,如果我想在 mysql 中显示任何 Student_id 4 的同级,那么它应该显示:
1
2
6
15
我尝试了以下查询,但它只显示 1 和 15: 预先感谢所有伟大的人
SELECT student_id
FROM `student_sibling`
WHERE student_id=4 or sibling_student_id=4
UNION
SELECT sibling_student_id,
FROM `student_sibling`
WHERE student_id=4 or sibling_student_id=4
最佳答案
如果您使用 MySQL 8.0 或更高版本,您可以使用以下递归查询 -
WITH RECURSIVE CTE AS (SELECT student_id
FROM student_sibling
WHERE sibling_student_id=4
UNION
SELECT S.student_id
FROM CTE C
JOIN student_sibling S ON S.sibling_student_id = C.student_id)
SELECT student_id FROM CTE
ORDER BY student_id;
Here是 fiddle 。
关于mysql - 如何找到学生的 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58526491/