我有下表,表1显示所有用户,表2显示教师与学生的关系:
表1(用户):
ID name age
-------------
1 Al 30
2 Bob 5
3 Cam 6
4 Dan 7
Table2(类):
teacher_id student_id
----------------------
1 2
1 3
从本质上讲,这表明Al(id = 1)是Bob(id = 2)和Cam(id = 3)的老师。我想返回用户一行老师和他的学生。例如,如果我正在寻找Al(id = 1),我想返回Al及其学生(Bob和Cam)的用户信息。我以为是
SELECT * FROM users
LEFT JOIN classes ON users.id=classes.teacher_id
WHERE id=1 OR teacher_id=1
但是我知道这一定是错误的,因为“ teacher_id = 1”无法从classes.student_id获取值。它应该是“ ... WHERE id = {来自Teacher_id = 1的班级的学生ID”。你如何做到的?
答案 0 :(得分:1)
您可以使用类似的查询来显示按老师姓名搜索的学生。
SELECT u.* FROM users u
where u.id IN (
SELECT t.student_id
FROM classes t
LEFT JOIN users tu ON t.`teacher_id` = tu.id
WHERE tu.name = 'Al'
);
样品
MariaDB [bernd]> SELECT * from users;
+----+------+------+
| id | name | age |
+----+------+------+
| 1 | Al | 30 |
| 2 | Bob | 5 |
| 3 | Cam | 6 |
| 4 | Dan | 7 |
+----+------+------+
4 rows in set (0.00 sec)
MariaDB [bernd]> SELECT * FROM classes;
+----+------------+------------+
| id | teacher_id | student_id |
+----+------------+------------+
| 1 | 1 | 2 |
| 2 | 1 | 3 |
+----+------------+------------+
2 rows in set (0.00 sec)
MariaDB [bernd]> SELECT u.* FROM users u
-> where u.id IN (
-> SELECT t.student_id
-> FROM classes t
-> LEFT JOIN users tu ON t.`teacher_id` = tu.id
-> WHERE tu.name = 'Al'
-> );
+----+------+------+
| id | name | age |
+----+------+------+
| 2 | Bob | 5 |
| 3 | Cam | 6 |
+----+------+------+
2 rows in set (0.00 sec)
MariaDB [bernd]>
答案 1 :(得分:0)
尝试此查询
SELECT * FROM classes
LEFT JOIN user ON classes.teacher_id= users.id
WHERE classes.teacher_id=1 or user.id = 1
答案 2 :(得分:0)
您可以将classes
加入到users
的2个副本中:
select u1.name teacher, u2.name student
from classes c
inner join users u1 on u1.id = c.teacher_id
inner join users u2 on u2.id = c.student_id
请参见demo。
结果:
| teacher | student |
| ------- | ------- |
| Al | Bob |
| Al | Cam |
或者如果您想用逗号分隔每个老师的所有学生的名单:
select u1.name teacher, group_concat(u2.name) students
from classes c
inner join users u1 on u1.id = c.teacher_id
inner join users u2 on u2.id = c.student_id
group by teacher
请参见demo。
结果:
| teacher | students |
| ------- | -------- |
| Al | Bob,Cam |