我完全正在使用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
有没有办法查询一次并在这两个地方重复使用它?
答案 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%'