下面是我的 SQL Server 查詢,效果很好,但正如您所見,我多次獲取同一行。有沒有辦法通過只做一次 SELECT 來優化它?謝謝。
SELECT TOP 1 1
FROM some_table
WHERE col1 = @col1
AND (col2 IN ('N', 'C', 'U') OR
col3 != (SELECT t.col3 FROM some_table t
WHERE t.id = id AND t.revision_id = revision_id - 1) OR
col4 != (SELECT t.col4 FROM some_table t
WHERE t.id = id AND t.revision_id = revision_id - 1) OR
col5 != (SELECT t.col5 FROM some_table t
WHERE t.id = id AND t.revision_id = revision_id - 1) OR
col6 != (SELECT t.col6 FROM some_table t
WHERE t.id = id AND t.revision_id = revision_id - 1)
)
注意:我只需要查看是否存在一個這樣的列(請參閱SELECT 1 1),這很可能是1大多數時候。所以我不想加入有數百萬行的表。
uj5u.com熱心網友回復:
首先,子查詢中的列名有錯誤。請參見限定子查詢中的列名
陳述句中的列名由同一級別的 FROM 子句中參考的表隱式限定。
因此,所有這些列都屬于t:t.id=id AND t.revision_id=revision_id-1
和查詢:
SELECT TOP 1 1
FROM some_table s
WHERE col1=@col1
AND
(
col2 IN ('N','C','U') OR
EXISTS(SELECT * FROM some_table where id = s.id
AND revision_id = s.revision_id - 1 AND
(col3 != s.col3 OR col4 != s.col4 OR col5 != s.col5 OR col6 != s.col6)
)
)
uj5u.com熱心網友回復:
您可以使用apply此處從相關行中選擇多個列。
這只是您需要的近似值,因為您沒有提供任何示例資料和預期結果。如果apply可以回傳多行,您可能需要將 atop (1)與適當的order by子句或聚合一起使用:
select *
from some_table t
outer apply (
select col3, col4, col5, col6
from some_table t2
where t2.id = t.id AND t2.revision_id = t.revision_id-1
)t2
where col1 = @col1
and (
col2 IN ('N','C','U') or
t.col3 != t2.col3 or
t.col4 != t2.col4 or
t.col5 != t2.col5 or
t.col6 != t2.col6
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489855.html
