重用已经选择的SQL查询结果的一部分 - 也就是说不重复自己

时间:2015-02-21 11:07:19

标签: sql sql-server

我完全正在使用SQL查询:

SELECT 
    Product.ID 
FROM 
    Product WITH (NOLOCK) 
WHERE 
    Product.Type = 1 AND Product.No = '123456789'

UNION 

SELECT 
    Description.ID 
FROM 
    Description WITH (NOLOCK) 
WHERE 
    Description.Opis LIKE '%hello%'
    AND Description.ID IN (SELECT Product.ID 
                           FROM Product WITH(NOLOCK) 
                           WHERE Product.Type = 1)

但我担心重复以下

SELECT Product.ID 
FROM Product WITH(NOLOCK) 
WHERE Product.Type = 12

有没有办法查询一次并在这两个地方重复使用它?

2 个答案:

答案 0 :(得分:0)

使用公用表表达式(cte):

with cte as (
SELECT Product.ID, Product.No 
FROM Product WITH(NOLOCK)
WHERE Product.Type = 1
)
SELECT ID
FROM cte
WHERE No = '123456789'

UNION

SELECT Description.ID
FROM Description WITH(NOLOCK)
WHERE Description.Opis LIKE '%hello%'
  AND Description.ID IN (SELECT ID from cte)
顺便说一句,也许你想要UNION ALL而不是UNION? (应该保留还是删除重复的行?)

答案 1 :(得分:0)

也可以使用表变量。还添加了UNION的第二部分:

DECLARE @ProductTemp TABLE (Id int, No int)

INSERT INTO @ProductTemp
SELECT Product.Id, Product.No
FROM Product WITH(NOLOCK)
WHERE Product.Type = 1

SELECT ID 
FROM @ProductTemp
WHERE No = '123456789'
UNION 
SELECT Description.ID
FROM Description WITH (NOLOCK)
INNER JOIN @ProductTemp AS p ON Description.ID = p.ID
WHERE Description.Opis LIKE '%hello%'