0

我有以下 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

谢谢

4

2 回答 2

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
于 2012-04-19T22:06:31.213 回答
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

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

于 2012-04-20T04:46:41.483 回答