我有一个学生表链接到两个结构完全相同的分数表。唯一的不同是一个表存储高分,另一张表存储低分。现在我需要查询高分表和低分表,如果它来自高分表,它将列出所有带有学生姓名的科目分数,如果它来自低分表,那么它会列出名称为 student
的分数,并且我需要按时间对结果进行排序。
SELECT u.student_name,
a.subject1_score,
a.subject2_score,
a.subject3_score,
a.subject4_score,
a.subject5_score,
a.exam_date
FROM Student u
INNER JOIN High_Score_Table a
On u.student_id = a.student_id
ORDER BY a.exame_date = time
然后,对于low_score_Table
,我将有几乎相同的查询,除了学生姓名默认等于Student
。
然后我需要将其放在一个列表中并按时间排序。我怎样才能做得更短、更好呢? 顺便说一句,我可以将两个表 low 和 high_score 合并为一个,并在其中添加一个名为“flag”的列,每当 flag 值等于“show”时,我就会显示学生姓名以及所有分数记录,否则“隐藏”我将只是显示“学生”和所有成绩记录。我怎样才能在一个查询中做到这一点?
最佳答案
听起来您需要一个UNION
,因为您要连接两个不同的结果集 - 一个来自 High_Score_Table
,另一个来自(大概)Low_Score_Table
>:
select s.student_name,
h.subject1_score,
h.subject2_score,
h.subject3_score,
h.subject4_score,
h.subject5_score,
h.exam_date
from High_Score_Table h
join Student s on h.student_id = u.student_id
union all
select 'student' as student_name,
l.subject1_score,
l.subject2_score,
l.subject3_score,
l.subject4_score,
l.subject5_score,
l.exam_date
from Low_Score_Table l
order by exam_date
这里的要点是联合排序中的 ORDER BY
子句对整个结果集进行排序 - 在本例中这正是您想要的。
关于php - 如何查询和排列两个相似的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28869896/