使用带有3个表的select,其中两个引用外键sqlite3

时间:2015-04-29 23:55:15

标签: sqlite

我创建了这些表格,现在,我想知道当时教授教授的科目有多少,我该怎么做?我已尝试使用JOIN,但我仍然不知道如何使用两个以上的表格,因为在这里我必须查看调度程序,然后查看教授ID和主题ID,以及然后查找id是什么主题名称以及教授命名该id是什么。

c.execute('''CREATE TABLE sections
                   (id_sect INTEGER PRIMARY KEY, name TEXT)''')

c.execute('''CREATE TABLE subjects
                   (id_subj INTEGER PRIMARY KEY, name TEXT, career TEXT)''')

c.execute('''CREATE TABLE professors
                   (id_p INTEGER PRIMARY KEY, name TEXT, lastname TEXT)''')
c.execute('''CREATE TABLE scheduler
                   (id_sch INTEGER PRIMARY KEY, id_sect INTEGER, id_subj INTEGER, id_p INTEGER, Day TEXT, From_time INTEGER, To_time INTEGER,
                   FOREIGN KEY (id_sect) REFERENCES sections (id_sect)
                    FOREIGN KEY (id_subj) REFERENCES subjects (id_subj),
                    FOREIGN KEY (id_p) REFERENCES professors (id_p))''')

1 个答案:

答案 0 :(得分:0)

进行三方联接:

SELECT p.name, COALESCE(COUNT(DISTINCT s.id_subj), 0) AS subject_count
FROM professors AS p
LEFT JOIN scheduler AS sc ON p.id_p = sc.id_p
LEFT JOIN subjects AS s ON sc.id_subj = s.id_subj
GROUP BY p.id_p

我使用了LEFT JOIN,以便显示没有教授任何科目的教授。

实际上,您甚至不需要加入subjects表,因为主题ID位于scheduler表中。您不需要主题名称来计算教授教授的科目数量,ID就足够了。

SELECT p.name, COALESCE(COUNT(DISTINCT sc.id_subj), 0) AS subject_count
FROM professors AS p
LEFT JOIN scheduler AS sc ON p.id_p = sc.id_p
GROUP BY p.id_p