【问题标题】:SQL - Select Values From A Table Where A Corresponding Value Matches The Results Of Another Select StatementSQL - 从对应值与另一个选择语句的结果匹配的表中选择值
【发布时间】:2021-04-27 18:56:56
【问题描述】:

由于标题很混乱,请允许我澄清一下。在这种情况下,我试图选择 10 年级学生的所有 parentemails。但是,学生的年级存储在另一个表中,使得 select 语句相当棘手。

这是我目前的尝试,我希望它能突出我遇到的障碍。

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

【问题讨论】:

    标签: python mysql sql sqlite select


    【解决方案1】:

    如果我理解正确,你只需要join

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

    【讨论】:

      【解决方案2】:

      一种方法是:

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

      【讨论】:

        猜你喜欢
        • 2021-08-13
        • 1970-01-01
        • 2021-08-04
        • 2019-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-23
        • 1970-01-01
        相关资源
        最近更新 更多