[英]SQL query: select into with join on 2 columns
In SQL Server 2014 ... 在SQL Server 2014中...
I am trying to find the rows in table 'new' that do not exist in table 'old'. 我试图在表“新”中查找表“旧”中不存在的行。 I want to take these new rows and stuff them into a third table that I create.
我想将这些新行填充到我创建的第三个表中。 Table 'new' has a primary key composed of two columns, MakeId and ModelId.
表“ new”的主键由两列组成:MakeId和ModelId。 The following SQL runs, but gives me vastly too many rows.
下面的SQL运行,但是给了我太多行。 Obviously, I am doing something wrong.
显然,我做错了。
select
new.MakeId ,
new.MageMakeId ,
new.ModelId ,
new.MageModelId
into BiUpdater..TranslateModel
from Mage_Production..TranslateModel new
left outer join BiLoader..TranslateModel old0 on new.MakeId = old0.MakeId
left outer join BiLoader..TranslateModel old1 on new.ModelId = old1.ModelId
go
My guess is that you want only one join using both columns: 我的猜测是,您只希望同时使用两列进行联接:
select new.MakeId, new.MageMakeId, new.ModelId, new.MageModelId
into BiUpdater..TranslateModel
from Mage_Production..TranslateModel new left outer join
BiLoader..TranslateModel old
on new.MakeId = old.MakeId and new.ModelId = old.ModelId
where old.MakeId is null;
More importantly, though, you need the where
clause to get the non-matches. 不过,更重要的是,您需要
where
子句来获取不匹配项。
EDIT: 编辑:
If you are looking for rows that don't match either MakeId
or ModelId
, then perhaps this is really what you want: 如果您要查找与
MakeId
或ModelId
不匹配的行,那么也许这确实是您想要的:
select new.MakeId, new.MageMakeId, new.ModelId, new.MageModelId
into BiUpdater..TranslateModel
from Mage_Production..TranslateModel new left outer join
BiLoader..TranslateModel old1
on new.MakeId = old1.MakeId left join
BiLoader..TranslateModel old2
on new.ModelId = old2.ModelId
where old1.MakeId is null and old2.ModelId is null;
You might want an or
instead of and
, in which case use select distinct
. 您可能希望使用
or
代替and
,在这种情况下,请select distinct
。
There is a SQL statement called EXCEPT that does this. 有一个称为EXCEPT的SQL语句可以执行此操作。 here is a link- http://msdn.microsoft.com/en-us/library/ms188055.aspx
这是一个链接-http: //msdn.microsoft.com/en-us/library/ms188055.aspx
Your right hand table would be 'new' and your left hand table would be 'old'. 您的右手桌将是“新的”,而您的左手桌将是“旧的”。
select *
into BiUpdater..TranslateModel
from (
select new.*
from Mage_Production..TranslateModel new
EXCEPT
select old.*
from BiLoader..TranslateModel old
)
Alternatively you could use a left join to do this: 或者,您可以使用左联接执行此操作:
select new.*
into BiUpdater..TranslateModel
from Mage_Production..TranslateModel new left join BiLoader..TranslateModel old
on new.MakeId = old.MakeId and new.ModelId = old.ModelId
where old.MakeId is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.