简体   繁体   中英

SQL - Select Values From A Table Where A Corresponding Value Matches The Results Of Another Select Statement

Since the title is quite confusing, allow me to clarify. In this instance, I am trying to select all parentemails of year 10 students. However, the year grade of the students are stored in another table, making the select statement rather tricky.

This is my attempt so far, I hope it highlights the roadblock I am at.

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*
    """

If I understand correctly, you just want join :

SELECT sc.parentemail
FROM student s JOIN
     studentcontact sc 
     ON s.code = sc.studentcode 
WHERE s.year = 10

One way to do this is:

SELECT parentemail
FROM studentcontact
WHERE studentcode IN (
    SELECT code
    FROM student
    WHERE year='10'
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM