使用SQL查询限制返回的唯一记录

时间:2017-07-02 08:15:49

标签: sql ms-access

我正在使用 Microsoft Access 来设计一个查询(我最终会在我的 MFC 应用程序中提取和使用。到目前为止,我有这个:

SQL Design

SQL视图是:

SELECT [Congregation Speaker Talks].talkno, [Congregation Speaker Talks].congregation
FROM [Congregation Speaker Talks]
WHERE ((([Congregation Speaker Talks].congregation)<>'Keynsham'))
ORDER BY [Congregation Speaker Talks].talkno;

目前的结果是:

Snippet of SQL results

所以它正在运行,因为没有列出值 Keynsham 的记录。但正如你所看到的那样,来自不同会众的多位发言者给出了第1号讲话。我只希望这个号码出现一次。我尝试使用DISTINCT但它不起作用。

更新

这有点帮助:

SQL "select where not in subquery" returns no results

我向您展示了我的所作所为,但我希望避免在表格中实际添加查询。

第1步 我创建了一个查询并将其保存为KeynshamTalks

SELECT [Public Talk Titles].[Talk Number]
FROM [Public Talk Titles] INNER JOIN [Congregation Speaker Talks] ON [Public Talk Titles].[Talk Number] = [Congregation Speaker Talks].talkno
WHERE ((([Congregation Speaker Talks].congregation)="Keynsham"))
ORDER BY [Public Talk Titles].[Talk Number], [Congregation Speaker Talks].congregation;

此查询返回会众 IS 设置为 Keynsham 的所有会众发言人谈话编号的列表。

第2步 接下来,我在公共对话标题表格上创建了​​一个新查询。该表只有一次通话号码。我使用KeynshamTalks查询的结果作为子查询:

SELECT *
FROM [Public Talk Titles]
WHERE ((([Public Talk Titles].[Talk Number]) Not In (SELECT [Talk Number]
FROM
[KeynshamTalks]
)))
ORDER BY [Public Talk Titles].[Talk Number];

这很有效。结果正是我想要看到的。但是,如何将第一个查询直接移动到第二个查询中,以便它只是一个查询?

2 个答案:

答案 0 :(得分:1)

您应该使用NOT EXISTS而非NOT IN编写查询:

SELECT ptt.*
FROM [Public Talk Titles] as ptt
WHERE NOT EXISTS (SELECT 1
                  FROM [Congregation Speaker Talks] as cst
                  WHERE ptt.[Talk Number] = cst.talkno AND
                        cst.congregation = "Keynsham"
                 )
ORDER BY ptt.[Talk Number];

注意表别名(并删除不需要的括号)使查询更容易编写和读取。

如果您只想要一个会话子集,那么在外部查询中添加WHERE子句。

答案 1 :(得分:0)

这就是我想要的:

SELECT *
FROM [Public Talk Titles]
WHERE ((([Public Talk Titles].[Talk Number]) Not In (
SELECT [Public Talk Titles].[Talk Number]
FROM [Public Talk Titles] INNER JOIN [Congregation Speaker Talks] ON [Public Talk Titles].[Talk Number] = [Congregation Speaker Talks].talkno
WHERE ((([Congregation Speaker Talks].congregation)="Keynsham"))
)))
ORDER BY [Public Talk Titles].[Talk Number];