Python SQL-从对应值与另一个Select语句的结果匹配的表中选择值
由于标题相当混乱,请允许我澄清。在本例中,我尝试选择10年级学生的所有家长电子邮件。但是,学生的年级存储在另一个表中,这使得select语句相当棘手 这是我迄今为止的尝试,我希望它突出了我所处的障碍Python SQL-从对应值与另一个Select语句的结果匹配的表中选择值,python,mysql,sql,sqlite,select,Python,Mysql,Sql,Sqlite,Select,由于标题相当混乱,请允许我澄清。在本例中,我尝试选择10年级学生的所有家长电子邮件。但是,学生的年级存储在另一个表中,这使得select语句相当棘手 这是我迄今为止的尝试,我希望它突出了我所处的障碍 conn = sqlite3.connect('test.db') c = conn.cursor() # Makes tables c.execute( """ CREATE TABLE IF NOT EXISTS student (
conn = sqlite3.connect('test.db')
c = conn.cursor()
# Makes tables
c.execute(
"""
CREATE TABLE IF NOT EXISTS student (
year INTEGER,
code INTEGER,
PRIMARY KEY (code)
)
""")
c.execute(
"""
CREATE TABLE IF NOT EXISTS studentcontact (
contactcode INTEGER,
studentcode INTEGER,
parentemail TEXT,
PRIMARY KEY (contactcode),
FOREIGN KEY (studentcode) REFERENCES student(code)
)
""")
c.execute("""
INSERT OR REPLACE INTO student (code, year) VALUES
(501, 9),
(502, 10),
(503, 10)
""")
c.execute("""
INSERT OR REPLACE INTO studentcontact (contactcode, studentcode, parentemail) VALUES
(401, 501, "bobjones@email.com"),
(402, 502, "billwilliams@email.com"),
(403, 503, "sallydavidson@email.com")
""")
### -- QUERY HERE -- ##
# My attempt so far
query = """
SELECT code FROM student WHERE year ='10'
SELECT parentemail FROM studentcontact WHERE studentcode = *results from select statement above*
"""
如果我理解正确,您只想加入:
SELECT sc.parentemail
FROM student s JOIN
studentcontact sc
ON s.code = sc.studentcode
WHERE s.year = 10
一种方法是:
SELECT parentemail
FROM studentcontact
WHERE studentcode IN (
SELECT code
FROM student
WHERE year='10'
)