MySQL Query解析两个表,两个字段

时间:2012-11-09 13:42:38

标签: mysql sql

数据库名称=大学

table1: university_info
field = university_name, student_number
e.g. values:

university_name          student_number
USC                      12345
USC                      54321
UW                       23456
UW                       65432

table2: student_info
field = student_number, student_test_scores
e.g. values:

student_number           student_test_scores
12345                    50
12345                    60
54321                    70
54321                    80
23456                    90
23456                    92
65432                    90
65432                    100

我上面有两张桌子。让我们打电话给数据库大学。我想在第一个查询中解析并输出大学名称,学号和学生考试成绩。

Example of first query:
e.g result
USC   12345   50
USC   12345   60
USC   54321   70
USC   54321   80
UW    23456   90
UW    23456   92
UW    65432   90
UW    65432  100

在第二个查询中,我想要相同的输出,但这次是更大的学生考试成绩。

Example of second query:
USC 12345  60
USC 54321  80
UW  23456  92
UW  65432 100

一旦我们获得最高的学生考试成绩,我们需要在第三个查询中平均考试成绩并输出最高学生考试成绩的平均值。

Example of third query:
Average test scores = 83

这是我到目前为止在第二个查询中所拥有的内容。我无法弄清楚如何添加名称:

mysql> select student_info.student_number, student_info.student_test_scores
    -> from student_info
    -> where (student_number='12345' and student_test_scores > 50)
    -> or (student_number='54321' and student_test_scores > 70)
    -> or (student_number='23456' and student_test_scores > 90)
    -> or (student_number='65432' and student_test_scores > 90)
    -> ;
+----------------+---------------------+
| student_number | student_test_scores |
+----------------+---------------------+
|          12345 |                  60 |
|          54321 |                  80 |
|          23456 |                  92 |
|          65432 |                 100 |
+----------------+---------------------+
4 rows in set (0.00 sec)

我知道有一种方法可以更好地完成上述3个查询。我只是不知道该怎么做。谁能帮我?提前谢谢。

1 个答案:

答案 0 :(得分:1)

SQL非常擅长这样做。

您需要使用GROUP BY语法,以及聚合函数MAX和AVG。

SELECT u.university_name, s.student_number, s.student_test_scores 
FROM student_info AS s
INNER JOIN university_info AS u ON s.student_number = u.student_number 
ORDER BY u.university_name, s.student_number, s.student_test_scores

SELECT u.university_name, s.student_number, MAX(s.student_test_scores) 
FROM student_info AS s
INNER JOIN university_info AS u ON s.student_number = u.student_number 
GROUP BY u.university_name, s.student_number
ORDER BY u.university_name, s.student_number

SELECT AVG(a.student_test_scores)
FROM (
    SELECT u.university_name, s.student_number, MAX(s.student_test_scores) AS student_test_scores
    FROM student_info AS s
    INNER JOIN university_info AS u ON s.student_number = u.student_number 
    GROUP BY u.university_name, s.student_number
) AS a