如何比较不同表中的两个INTEGER列?

时间:2019-04-14 08:55:26

标签: sql postgresql

学校的校长告诉您,他怀疑学校里的很多学生都比他们的课程老师年龄大。校长要求您找出课程老师比他们年轻的学生人数。如果某个学生已注册某门课程,则该课程的课程老师将被视为该学生的课程老师。

我已经用表编写了一个数据库结构。

create table Teacher 
(
  id INTEGER PRIMARY KEY,
  name VARCHAR(50),
  age INTEGER
);

create table Student 
(
  id INTEGER PRIMARY KEY,
  name VARCHAR(50),
  role INTEGER,
  age INTEGER
);

create table Course 
(
  id INTEGER PRIMARY KEY,
  title VARCHAR(50),
  course_teacher INTEGER REFERENCES Teacher(id)
);

create table Enrolment 
(
  course INTEGER REFERENCES Course(id),
  student INTEGER REFERENCES Student(id)
);

我期待着一些年龄比他们的课程老师高的学生。

1 个答案:

答案 0 :(得分:0)

要获得与一位年轻老师一起学习课程中有多少学生的概述:

SELECT t.id, count(distinct s.id) filter (WHERE s.age > t.age)
FROM teacher t
JOIN course c ON (t.id = c.course_teacher)
JOIN enrolment e ON (e.course = c.id)
JOIN student s ON (s.id = e.student)
GROUP BY 1;

...将提供类似的内容:

 id | count 
----+-------
  1 |     3
  2 |     1
  3 |     0
...

如果您想获得更多见解,只需将课程添加到其中,例如:

SELECT t.id, t.name, c.id, c.title, count(s.*) filter (WHERE s.age > t.age)
FROM teacher t
JOIN course c ON (t.id = c.course_teacher)
JOIN enrolment e ON (e.course = c.id)
JOIN student s ON (s.id = e.student)
GROUP BY 1, 2, 3, 4;

...导致:

 id |       name       | id |  title  | count 
----+------------------+----+---------+-------
  1 | Donata Barna     |  1 | Maths   |     3
  3 | Katsurou Plourde |  3 | History |     0
  2 | Natela Kardos    |  2 | Physics |     1
...

...并且如果您需要知道哪些学生比哪个课程的老师年龄大,请使用以下方法:

SELECT s.id, s.name, array_agg(c.title) filter (WHERE s.age > t.age)
FROM teacher t
JOIN course c ON (t.id = c.course_teacher)
JOIN enrolment e ON (e.course = c.id)
JOIN student s ON (s.id = e.student)
GROUP BY 1 ORDER BY 1;

...导致:

 id |       name       |    array_agg    
----+------------------+-----------------
  1 | Oda Peters       | 
  2 | Lourens Strand   | {Maths,Physics}
  3 | Haf Giannopoulos | {Maths}
  4 | Fuat Nervi       | {Maths}
  5 | Hadil Giffard    | 
...

使用的测试数据:

INSERT INTO teacher (id, name, age) VALUES
    (1, 'Donata Barna', 25),
    (2, 'Natela Kardos', 31),
    (3, 'Katsurou Plourde', 53)
;

INSERT INTO student (id, name, age) VALUES
    (1, 'Oda Peters', 19),
    (2, 'Lourens Strand', 32),
    (3, 'Haf Giannopoulos', 29),
    (4, 'Fuat Nervi', 26),
    (5, 'Hadil Giffard', 25)
;

INSERT INTO course (id, title, course_teacher) VALUES
    (1, 'Maths', 1),
    (2, 'Physics', 2),
    (3, 'History', 3)
;

INSERT INTO enrolment (course, student)
SELECT c.id AS course, s.id AS student
FROM generate_series(1,3) AS c(id)
CROSS JOIN generate_series(1,5) AS s(id);