添加子查询 - SQL Server 2008

时间:2012-04-19 21:58:47

标签: sql-server-2008 tsql

我有以下SQL查询,但这不是我想要的:

SELECT 
    TOP (20) Attribs.ImageID AS ItemID 
FROM 
    Attribs 
LEFT OUTER JOIN 
    Items ON Attribs.ImageID = Items.ImageID 
WHERE
    (attribID IN ('a','b','c','d','e')) 
    AND (deleted NOT IN (1,2)) 
    AND Attribs.attribID = 'a' AND Attribs.attribID = 'b'
GROUP BY 
    Attribs.ImageID 
ORDER BY 
    COUNT(DISTINCT attribID) DESC

我需要的是查询

   AND Attribs.attribID = 'a' AND Attribs.attribID = 'b'

首先,然后根据上面的查询结果继续WHERE子句。

这可以实现使用子查询吗?

我正在使用SQL Server 2008

谢谢

2 个答案:

答案 0 :(得分:0)

您是否希望针对性能问题执行此操作?因为拆分它不会改变结果。

无论如何,你可以这样做:

SELECT TOP (20) rn_Attribs.ImageID AS ItemID 
FROM (SELECT * 
      FROM Attribs
      WHERE Attribs.attribID = '123' AND Attribs.attribID = '456') rn_Attribs 
LEFT OUTER JOIN Items ON rn_Attribs.ImageID = Items.ImageID 
WHERE(attribID IN ('a','b','c')) 
    AND (deleted NOT IN (1,2)) 
GROUP BY rn_Attribs.ImageID 
ORDER BY COUNT(DISTINCT attribID) DESC

答案 1 :(得分:0)

我并不完全明白为什么你想先在另一个之前执行 这个查询,但你可以使用公用表表达式(CTE) - 这样的事情:

;WITH FirstQuery AS
(
    SELECT a.ImageId
    FROM dbo.Attribs a
    WHERE a.attribID = 'a' AND a.attribID = 'b'
)
SELECT 
    TOP (20) a.ImageID AS ItemID 
FROM 
    dbo.Attribs a
INNER JOIN
    FirstQuery fq ON a.ImageId = fq.ImageId  
LEFT OUTER JOIN 
    dbo.Items i ON a.ImageID = i.ImageID 
WHERE
    (attribID IN ('a','b','c','d','e')) 
    AND (deleted NOT IN (1,2)) 
GROUP BY 
    a.ImageID 
ORDER BY 
    COUNT(DISTINCT attribID) DESC

有了这个,你首先从CTE中的ImageID表中选择dbo.Attribs,然后将该结果集与表的结果连接起来并加入到Items表。