我必须有两个单独的表格(表A和表B)。 表A有大约15列,唯一重要的是[名字]和[姓氏]。 表B中有更多列,而且我唯一关注的是FirstName和LastName(表B' s字段不包含空格,表A' s)。
他们都在Access中,我试图编写一个查询,可以找到表B中不在表A中的人。我非常喜欢SQL,但这里&#39我想出了什么:
SELECT ([Table A].[First Name] + [Table B].[Last Name]) AS FullName
FROM [Table A]
LEFT JOIN [Table B]
ON [Table A].FullName=[Table B].([First Name] + [Table B].[Last Name]) AS FullName
WHERE [Table A].FullName IS NULL;
我不想让我试图为表B中的名字+姓氏制作别名,但我不知道我是怎么做的。
答案 0 :(得分:1)
试试这个:
SELECT ([Table A].[First Name] + ' ' + [Table A].[Last Name]) AS FullName
FROM [Table B]
LEFT OUTER JOIN [Table A]
ON [Table A].[First Name]=[Table B].[First Name] AND [Table B].[Last Name] = [Table A].[Last Name]
WHERE [Table A].[First Name] IS NULL AND [Table A].[Last Name] IS NULL
答案 1 :(得分:0)
SELECT ([Table A].[First Name] + [Table B].[Last Name]) AS FullName
FROM [Table A]
RIGHT OUTER JOIN [Table B]
ON [Table A].FullName= ([Table B].([First Name] + [Table B].[Last Name])
WHERE [Table A].FullName IS NULL;
这里的关键是使用外连接,它将为您提供表B中的所有记录,无论连接如何。然后,您可以使用WHERE
将其过滤到不匹配的记录答案 2 :(得分:0)
试试这个:
SELECT [B].[First Name] & " " & [B].[Last Name] AS FullName
FROM TableB AS B
WHERE [B].[First Name] & " " & [B].[Last Name] NOT IN
(SELECT [First Name] & " " & [Last Name] FROM TableA)
答案 3 :(得分:0)
建议:使用VIEW
来从数据元素名称中删除那些恼人的空格,提供一致的命名并连接全名属性,例如:
CREATE VIEW TableA
AS
SELECT [First Name] AS first_name,
[Last Name] AS last_name,
first_name + ' ' + last_name AS full_name
FROM [Table A];
CREATE VIEW TableB
AS
SELECT FirstName AS first_name,
LastName AS last_name,
first_name + ' ' + last_name AS full_name
FROM [Table B];
SELECT *
FROM TableB AS B
WHERE NOT EXISTS (
SELECT *
FROM TableA AS A
WHERE B.full_name = A.full_name
);
注意CREATE VIEW
需要ANSI-92 Query Mode,例如使用ADO连接。
P.S。 “表B中不在表A中的人”的运算符称为semi difference a.k.a. antijoin。