将SQL查询扩展到其他表

时间:2014-06-15 14:19:16

标签: sql sql-server

以下查询返回表_621中的代码,名称,标准和数量,这些不在表组件中。

SELECT DISTINCT a.Code
    ,a.Designation
    ,a.Standard
    ,a.Quantity
FROM Table_621 AS a
WHERE NOT EXISTS (SELECT * 
                  FROM Components 
                  WHERE Components.Code = a.Code)

我需要在同一个查询中同时选择其他表:Table_333,Table_853等。 如何扩展上述查询以从更多表中进行选择?

1 个答案:

答案 0 :(得分:0)

您可以使用UNION ALL

SELECT DISTINCT a.Code, a.Designation, a.Standard, a.Quantity FROM Table_621 AS a
WHERE NOT EXISTS (SELECT * FROM Components where Components.Code = a.Code)
UNION ALL
SELECT DISTINCT a.Code, a.Designation, a.Standard, a.Quantity FROM Table_333 AS a
WHERE NOT EXISTS (SELECT * FROM Components where Components.Code = a.Code)
UNION ALL
SELECT DISTINCT a.Code, a.Designation, a.Standard, a.Quantity FROM Table_853 AS a
WHERE NOT EXISTS (SELECT * FROM Components where Components.Code = a.Code)