我想创建一个临时表来保存来自所有共享此通用gid的许多不同表中的唯一gid值。我目前的写法如下:
CREATE TABLE #QHP_Unique
(some_gid INT)
INSERT INTO #QHP_Unique
SELECT DISTINCT PR.some_gid
FROM Table_PR PR
INSERT INTO #QHP_Unique
SELECT DISTINCT PX.some_gid
FROM Table_PX PX
LEFT OUTER JOIN #QHP_Unique QS ON PX.some_gid= QS.some_gid
WHERE QS.some_gid IS NULL;
INSERT INTO #QHP_Unique
SELECT DISTINCT COP.some_gid
FROM Table_COP COP
LEFT OUTER JOIN #QHP_Unique QS ON COP.some_gid= QS.some_gid
WHERE QS.some_gid IS NULL;
以及其中3个插入表以及另外3个表。
是否可以在单个查询中编写所有这些内容?
答案 0 :(得分:4)
您可以使用UNION
进行操作,它将从组合表中选择DISTINCT
个值:
CREATE TABLE #QHP_Unique
(some_gid INT)
INSERT INTO #QHP_Unique (some_gid)
SELECT some_gid
FROM Table_PR
UNION
SELECT some_gid
FROM Table_PX
UNION
SELECT some_gid
FROM Table_COP