您好我有两张表格具有以下结构
学生
+------+------+------+-------+------+------+
| 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,CO14 = Col3中的标记,Col5 = subjectCpde,Col6 = Col5的标记
另一张叫做主题的表
+------+-----------+
| Col1 | Col2 |
+------+-----------+
| 20 | English |
| 21 | Maths |
| 25 | Chemistry |
| 26 | Physics |
+------+-----------+
此处Col1 =主题代码,COl2 =主题名称 在学生表中引用了。
现在我的查询应该按如下方式重新调整结果。如何实现?
+---------+--------+------+
| Subject | Marks | Name |
+---------+--------+------+
| English | 80 | Hari |
| Maths | 81 | Hari |
+---------+--------+------+
答案 0 :(得分:0)
你可以试试这个。
使用两个查询,首先按subjectCode
查询English
,按subjectCode
查询English
。然后使用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'