我有三个表,只有一个公共字段[Asset]。
一个表[tblAssets]包含我想要的所有字段。
但是,我想检查其他两个表并添加任何未出现在第一个表中的[资产]。
这将导致一条仅包含[资产]且其余字段为空白的新记录。
我当前的代码如下:
SELECT *, "Assets" AS [Source]
FROM [tblAssets]
UNION SELECT "BOM", [Asset], NULL, NULL, NULL, NULL, NULL, NULL
FROM [tblBOM]
UNION SELECT "WO", [Asset], NULL, NULL, NULL, NULL, NULL, NULL
FROM [tblWO];
这将按预期添加记录,但由于整个记录不是重复项,因此不会删除重复项。
我怀疑还有其他方法可以解决此问题,例如在特定条件下附加查询。
为明确起见,我想要显示多个数据源中所有[资产]的完整列表,但只需要[资产]表中出现的其余字段。
样本数据:
tblAssets-
Asset Type Unit
P1 2 1
M1 1 2
tblBOM-
Comp Asset Qty
1 P1 1
2 P2 2
tblWO-
WO Asset Cost
1 P1 100
2 C1 200
电流输出
Source Asset Type Unit
Assets P1 2 1
Assets M1 1 2
BOM P1
BOM P2
WO P1
WO C1
所需的输出
Source Asset Type Unit
Assets P1 2 1
Assets M1 1 2
BOM P2
WO C1
答案 0 :(得分:0)
从表tblBOM
和tblWO
中选择表Asset
中不存在的tblAssets
的所有不同值:
SELECT "Assets" AS [Source], * FROM [tblAssets]
UNION
SELECT "BOM" AS [Source], [Asset], NULL, NULL, NULL, NULL, NULL, NULL FROM [tblBOM]
WHERE [Asset] NOT IN (SELECT DISTINCT [Asset] FROM [tblAssets])
UNION
SELECT "WO" AS [Source], [Asset], NULL, NULL, NULL, NULL, NULL, NULL FROM [tblWO]
WHERE [Asset] NOT IN (SELECT DISTINCT [Asset] FROM [tblAssets])
答案 1 :(得分:0)
。
SELECT "Assets" AS [Source], A.*
FROM [tblAssets] A
UNION SELECT "BOM", [Asset], NULL, NULL, NULL, NULL, NULL, NULL
FROM [tblBOM]
WHERE [Asset] not in (SELECT Asset FROM tblAssets)
and [Asset] not in (SELECT ASSET FROM [tblWO])
UNION SELECT "WO", [Asset], NULL, NULL, NULL, NULL, NULL, NULL
FROM [tblWO]
WHERE [Asset] not in (SELECT Asset FROM tblAssets)