来自多个表的MySQL SELECT查询

时间:2019-03-28 17:12:39

标签: mysql sql

我需要有关来自多个表的mySQL SELECT查询的帮助。我有四个表:学校,学科,学生和团队。

学校表格如下:

+------+---------+---------------+----------+
| id   | name    | discipline_id | pupil_id |
+------+---------+---------------+----------+
| 1    | one     |     2         |    5     |
+------+---------+---------------+----------+
| 2    | two     |     3         |    8     | 
+------+---------+---------------+----------+
| 3    | three   |     4         |    12    | 
+------+---------+---------------+----------+

学科表如下:

+------+---------+
| id   | name    | 
+------+---------+
| 1    | math    |
+------+---------+
| 2    | bio     |
+------+---------+
| 3    | liter   |
+------+---------+
| 4    | geo     |
+------+---------+

Teams表格如下:

+------+---------+---------------+-----------+
| id   | name    |   school_id   | member_id |
+------+---------+---------------+-----------+
| 1    | T1      |     1         |     3     |
+------+---------+---------------+-----------+
| 2    | T2      |     3         |     3     | 
+------+---------+---------------+-----------+
| 3    | T3      |     2         |     9     | 
+------+---------+---------------+-----------+

我需要通过“ member_id = 3”的“ SELECT from学科...”查询获得学科的结果是:

+-----------------+---------------+
| discipline_name | discipline_id |
+-----------------+---------------+
|      bio        |       2       |
+-----------------+---------------+
|      geo        |       4       |
+-----------------+---------------+

通过匹配成员所在的学校,然后再按学科进行培训,如果有意义的话...是否可以只使用一个mySQL查询?

类型:member_id 3 => school_id 1,3 =>学科ID =显示相关学科名称和ID,即2、4

非常感谢您...

1 个答案:

答案 0 :(得分:1)

您的目标不明确或对我没有意义。

但这是您真正要的:

SELECT
       s.discipline_id
       d.name
FROM teams t
LEFT JOIN school s
ON s.id = t.school_id
LEFT JOIN discipline d
ON d.id = s.discipline_id
WHERE t.member_id = 3