SubSelect Top 1或Left Join

时间:2015-10-15 15:43:09

标签: sql-server

我使用Top 1和where子句选择子选择。

我尝试通过执行子选择的左连接来优化选择,但查询时间花费更长时间。在这种情况下,subselect更好吗?我无法发布我的整个选择,因为它太长而且保密,但我会尝试重新创建以下重要部分:

子选择

SELECT 
(select top 1 colId FROM table1 WHERE col1 = b.Id and col2 = 3 Order by 1) Id3,
(select top 1 colId FROM table1 WHERE col1 = b.Id and col2 = 5 Order by 1) Id5,
(select top 1 colId FROM table1 WHERE col1 = b.Id and col2 = 7 Order by 1) Id7
FROM    table2 b

尝试使用左连接

SELECT 
    t1.colid id3,
    t2.colid id5,
    t3.colid id7
FROM    table2 b
LEFT JOIN (
        select colId, col1 FROM table1 WHERE col2 = 3
    ) t1 ON t1.col1 = b.Id 
LEFT JOIN (
        select colId, col1 FROM table1 WHERE col2 = 5
    ) t2 ON t1.col1 = b.Id 
LEFT JOIN (
        select colId, col1 FROM table1 WHERE col2 = 7
    ) t3 ON t1.col1 = b.Id 

有更好的方法吗?为什么左连接需要更长的查询时间?

1 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER

;WITH cte AS
(
    SELECT  a.colId,
            rn = ROWN_NUMBER() OVER (PARTITION BY a.col2 ORDER BY a.col1)
    FROM      table1 a
    LEFT JOIN table2 b on a.col1 = b.id
    WHERE   a.col2 IN (3,5,7)
)

SELECT *
FROM cte
WHERE rn = 1

这将为您提供每个col2值的第一行,您可以将所需的值限制为3,5,7。