如何查询和排列两个相似的表

时间:2015-03-05 04:16:30

标签: php mysql sql

我有一个学生表链接到两个得分表,它们是完全相同的结构。唯一不同的是,一个表将存储高分,另一个表存储低分。现在我需要查询高分和低分表,如果它来自高分表,它将列出所有科目分数与学生姓名,如果分数从低分表,则列出名称为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"的列。每当标志值等于"显示"然后我会显示所有得分记录的学生姓名,否则"隐藏"我将展示"学生"和所有得分记录。我怎么能在一个查询中做到这一点?

1 个答案:

答案 0 :(得分:1)

听起来你需要一个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子句对整个结果集进行排序 - 在这种情况下,这正是你想要的。