SQLite - 选择在另一个表中没有对应项的记录

时间:2013-08-16 08:14:47

标签: sqlite select

我有4张桌子:

CREATE TABLE People(
    id integer primary key autoincrement,
    'First Name' text,
    'Last Name' text,
);

CREATE TABLE Courses(
    id integer primary key autoincrement,
    'Course Name' text,
    'Course Refresh Rate' integer
);

CREATE TABLE [Course Enrolment](
    'Person ID' integer,
    'Course ID' integer,
    FOREIGN KEY ('Person ID') REFERENCES People(id),
    FOREIGN KEY ('Course ID') REFERENCES Courses(id)
);

CREATE TABLE [Course Participation](
    'Person ID' integer,
    'Course ID' integer,
    'Date Taken' text,
    FOREIGN KEY ('Person ID') REFERENCES People(id),
    FOREIGN KEY ('Course ID') REFERENCES Courses(id)
);

我正在尝试选择参加课程但未参加课程的学员(因此没有参加课程参与表中的记录),或者选择的课程超过了“课程刷新率”几年前。我写了一个select语句,但它没有按预期工作。

SELECT [First Name],
       [Last Name]
  FROM people AS p
       LEFT JOIN courses AS c
       JOIN [course enrolment] AS ce
       JOIN [course participation] AS cp
        ON p.id = ce.[Person ID] 
        AND p.id = cp.[Person ID] 
        AND c.id = ce.[Course ID] 
        AND c.id = cp.[Course ID]
  WHERE EXISTS(SELECT * FROM [Course Enrolment] as ce_2 WHERE ce_2.[Person ID] = p.id and ce_2.[Course ID] = c.id )
    AND ([date taken] < date( 'now', '-' || [course refresh rate] || ' year' )
    or NOT EXISTS(SELECT * FROM [Course Participation] WHERE cp.[Person ID] = p.id and cp.[Course ID] = c.id ))
;

我做错了什么?

2 个答案:

答案 0 :(得分:1)

如何过滤来自所有其他人的近期参与者: -

SELECT [First Name],
       [Last Name]
  FROM people AS p
  JOIN courses AS c
  JOIN [course enrolment] AS ce
    ON p.id = ce.[Person ID] 
   AND c.id = ce.[Course ID] 

MINUS

SELECT [First Name],
       [Last Name]
  FROM people AS p
  JOIN courses AS c
  JOIN [course enrolment] AS ce
  JOIN [course participation] AS cp
    ON p.id = ce.[Person ID] 
   AND p.id = cp.[Person ID] 
   AND c.id = ce.[Course ID] 
   AND c.id = cp.[Course ID] 
 WHERE [date taken] > date( 'now', '-' || [course refresh rate] || ' year') 

未经过测试

答案 1 :(得分:1)

SELECT DISTINCT p.id,
                p.[First Name],
                p.[Last Name]
FROM People AS p
JOIN [Course Enrolment] AS ce ON p.id = ce.[Person ID]
JOIN Courses AS c ON ce.[Course ID] = c.id
LEFT JOIN [Course Participation] AS cp ON cp.[Person ID] = p.id AND
                                          cp.[Course ID] = c.id
WHERE cp.[Date Taken] IS NULL
   OR cp.[Date Taken] < date('now', '-' || c.[Course Refresh Rate] || ' year')