如何比较不同表中的两个INTEGER列?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何比较不同表中的两个INTEGER列?相关的知识,希望对你有一定的参考价值。
学校校长告诉你,他怀疑学校里的很多学生比他们的课程老师年纪大。校长要求你找出学生的数量,他们的课程老师比他们年轻。如果学生注册了课程,那么该课程的课程教师将被视为该学生的课程教师。
我用表编写了一个数据库结构。
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)
);
我期待一些学生的年龄高于他们的课程老师。
答案
要了解有多少学生参加一个年轻教师的课程:
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);
以上是关于如何比较不同表中的两个INTEGER列?的主要内容,如果未能解决你的问题,请参考以下文章
如何匹配两个不同表中的列并将选定的列输出到 MySQL 中的第三个表?