在mssql中的WHERE子句中使用DISTINCT子句

时间:2014-02-12 19:57:42

标签: sql sql-server

我想从表1中选择(或更新某些记录)where distinct(make, model,category) = distinct(make, model,category) in table 2 我试过这个:

select * from t1 
having ( make, model, catcode) = (select  make, model, catcode from t2)

并尝试了这个:

select * from t1
where (make, model, catcode) in (select make, model, catcode from t2)

但两个都没有任何想法?

2 个答案:

答案 0 :(得分:4)

不幸的是,IN=仅支持单列结果。您可以使用EXISTS

执行所需操作
select * from t1 
WHERE EXISTS( 
    SELECT null FROM t2 
    WHERE t1.make = t2.make
      AND t1.model = t2.model
      AND t1.catcode= t2.catcode
)

答案 1 :(得分:2)

与存在类似,这只会获取t2中存在的t1记录。

select distinct
       t1.make, t1.model, t1.catcode
from t1 join t2 on (t1.make = t2.make
                    and t1.model = t2.model
                    and t1.catcode = t2.catcode)