[英]How to loop through rows in two tables and create a new set based on the merged results in SQL
Here is my obstacle. 这是我的障碍。
I have two tables. 我有两张桌子。 Table A contains more rows than Table B. I have to merge the results and if Table A does not contain a row from Table B then I insert it into the new set.
表A比表B包含更多的行。我必须合并结果,如果表A不包含表B的一行,则将其插入到新集合中。 If however, a row from Table A contains a row with the same primary key as Table B, the new set will take the row from Table B.
但是,如果表A中的行包含与表B具有相同主键的行,则新集将采用表B中的行。
Would this best be done in a cursor or is there an easier way to do this? 最好在游标中完成此操作,还是有更简单的方法来执行此操作? I ask because there are 20 million rows and while I am new to sql, i've heard cursors are expensive.
我问是因为有2000万行,而我是sql的新手,但我听说游标很昂贵。
Your phrasing is a little vague. 您的措词有点含糊。 It seems that you want everything from TableB and then rows from TableA that have no matching primary key in B. The following query solves this problem:
似乎您希望从TableB中获得所有内容,然后再从TableA中获得所有内容,而这些行都在B中没有匹配的主键。以下查询解决了此问题:
select *
from tableB union all
select *
from tableA
where tableA.pk not in (select pk from tableB)
Yep, cursors are expensive. 是的,游标很昂贵。
There's a MERGE
command in later versions of SQL that will do this in one shot, but it's sooo cumbersome. 更高版本的SQL中有一个
MERGE
命令,可以一次性完成此操作,但是非常麻烦。 Better to do it in two pieces - first: 最好分两步进行-首先:
UPDATE A SET
field1 = B.field1
,field2 = B.field2
, etc
FROM A JOIN B on B.id = A.id
Then: 然后:
INSERT A SELECT * FROM B --enumerate fields if different
WHERE B.id not in (select id FROM A)
An OUTER JOIN should do what you need and be more efficient than a cursor. 外部联接应该执行所需的操作,并且比游标更有效。 Try this query
试试这个查询
--first get the rows that match between TableA and TableB
INSERT INTO [new set]
SELECT TableB.* --or columns of your choice
FROM TableA LEFT JOIN TableB ON [matching key criteria]
WHERE TableB.[joining column/PK] IS NOT NULL
--then get the rows from TableA that don't have a match
INSERT INTO [new set]
SELECT TableA.* --you didn't say what was inserted if there was no matching row
FROM TableA LEFT JOIN TableB ON [matching key criteria]
WHERE TableB.[joining column/PK] IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.