我想创建一个临时表以从所有共享此常见的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个插入物。
有没有办法在单个查询中写下所有这些?
您可以使用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