嗨,我有两个具有以下结构的表

学生们

 +------+------+------+-------+------+------+
| Col1 | Col2 | Col3 | Col4  | Col5 | Col6 |
+------+------+------+-------+------+------+
|   01 | Hari | 20   |    80 |   21 |   81 |
|   02 | Nari | 20   |    67 |   21 |   76 |
|   02 | Lari | 25   |    87 |   26 |   96 |
+------+------+------+-------+------+------+


此处COl1 = ID,Col2 =名称,Col3 = SubjectCode,COl4 = Col3中的标记,Col5 = subjectCpde,Col6 = Col5的标记

还有另一个表叫做subject

+------+-----------+
| Col1 |   Col2    |
+------+-----------+
|   20 | English   |
|   21 | Maths     |
|   25 | Chemistry |
|   26 | Physics   |
+------+-----------+


此处Col1 =主题代码,COl2 =主题名称
在学生表中已被引用。

现在,我的查询应按以下方式返回结果。如何实现的?

+---------+--------+------+
| Subject |  Marks | Name |
+---------+--------+------+
| English |     80 | Hari |
| Maths   |     81 | Hari |
+---------+--------+------+

最佳答案

你可以试试看

使用两个查询,第一个查询subjectCodeEnglish,第二个查询subjectCodeEnglish。然后使用UNION ALL组合它们。

SELECT sub.Col2 as 'Subject',stu.Col4 as 'Marks',stu.Col2 as 'Name'
FROM Students stu
inner join subjects sub on sub.Col1 = stu.Col3
WHERE stu.Col2 = 'Hari'
UNION ALL
SELECT sub.Col2 as 'Subject',stu.Col6 as 'Marks',stu.Col2 as 'Name'
FROM Students stu
inner join subjects sub on sub.Col1 = stu.Col5
WHERE stu.Col2 = 'Hari'



  http://sqlfiddle.com/#!9/513fe5/17

关于mysql - 如何从表的单行中获取多行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49684594/

10-10 20:47