这是我创建的数据库:
students = [('TOM', 6120, 85),
('Jerry', 6110,86),
('Spike', 6120,55),
('Tyke',6110,73),
('Butch',6110,89),
('Toodle',6120,76)]
courses = [(6110,'Data Science I', 'LSB105'),
(6120,'Data Science II', 'LSB109')]
grading = [('A', 90, 100),
('B', 80,90),
('C',70,80)]
import sqlite3
conn = sqlite3.connect('example3.db')
c = conn.cursor()
c.execute('CREATE TABLE students(name TEXT, courseid INTEGER, score INTEGER)') #create a table
c.executemany('INSERT INTO students VALUES(?,?,?)', students)
c.execute('CREATE TABLE courses(courseid INTEGER, name TEXT, classroom TEXT)') #create a table
c.executemany('INSERT INTO courses VALUES(?,?,?)', courses)
c.execute('CREATE TABLE gradingscheme(letter TEXT, lower REAL, upper REAL)') #create a table
c.executemany('INSERT INTO gradingscheme VALUES(?,?,?)', grading)
conn.commit()
conn.close()
这到底是我想要的: final result
我是通过3个步骤完成的,我觉得我的方法太复杂了:
c.execute('''
CREATE view part1 AS
SELECT s.name,s.courseid,c.name AS coursename,classroom,score
FROM students AS s, courses AS c
WHERE s.courseid=c.courseid
''')
#Create another view "part2" to combine "part1" and table: "gradingscheme"
c.execute('''
CREATE view part2 AS
SELECT * FROM part1 , (SELECT * FROM gradingscheme AS g)
''')
#Get the final results
c.execute('''
SELECT name, courseid, coursename, classroom, score, letter
FROM part2
WHERE score BETWEEN lower AND upper
''')
那么,任何人都可以帮我缩短我的代码吗?感谢您的帮助!
答案 0 :(得分:0)
您不需要将JOIN放入视图中,也不需要将它们拆分为多个视图,每个视图都连接两个表。以下内容应与后一个代码段产生相同的结果:
SELECT s.name, s.courseid, c.name AS coursename, c.classroom, s.score, g.letter
FROM students AS s, courses AS c, gradingscheme AS g
WHERE s.courseid=c.courseid
AND s.score BETWEEN g.lower AND g.upper