1

我有 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 [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 ))
;

我做错了什么?

4

2 回答 2

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') 

未测试

于 2013-08-16T09:04:52.710 回答
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')
于 2013-08-16T09:08:47.320 回答