我试图在一个表(表A)中找到另一个表(表B)中不存在的行,然后将这些行插入到另一个表(表B)中。然而,两个表中都有多个重复的行,我想将新的额外重复作为要插入的新行计数。
当前的结构类似于:
表答:
+--------+-------+---------+
| prefix | fname | lname |
+--------+-------+---------+
| Mr | John | Smith |
| Mrs | Jane | Doe |
| Mr | John | Smith |
| Mrs | Jane | Doe |
| Mr | Bob | Jones |
| Mrs | Jane | Doe |
| Mr | John | Smith |
| Mrs | Sally | Johnson |
| Mr | Bob | Jones |
| Mrs | Alice | Apples |
+--------+-------+---------+
表B: (id is auto-increment)
+----+--------+-------+---------+
| id | prefix | fname | lname |
+----+--------+-------+---------+
| 1 | Mr | John | Smith |
| 2 | Mr | John | Smith |
| 3 | Mrs | Jane | Doe |
| 4 | Mr | Bob | Jones |
| 5 | Mrs | Sally | Johnson |
| 6 | Mrs | Sally | Johnson |
+----+--------+-------+---------+
NEW added的集合(表A中不在表B中的行)如下:
+--------+-------+--------+
| prefix | fname | lname |
+--------+-------+--------+
| Mrs | Jane | Doe |
| Mrs | Jane | Doe |
| Mr | John | Smith |
| Mrs | Alice | Apples |
+--------+-------+--------+
注意:现在"Mrs Sally johnson"的条目减少了,但我只关心相同行增加的次数,而不是减少的次数。
将这些插入表B后,允许id自动增加,表B看起来像这样:
+----+--------+-------+---------+
| id | prefix | fname | lname |
+----+--------+-------+---------+
| 1 | Mr | John | Smith |
| 2 | Mr | John | Smith |
| 3 | Mrs | Jane | Doe |
| 4 | Mr | Bob | Jones |
| 5 | Mrs | Sally | Johnson |
| 6 | Mrs | Sally | Johnson |
| 7 | Mrs | Jane | Doe |
| 8 | Mrs | Jane | Doe |
| 9 | Mr | John | Smith |
| 10 | Mrs | Alice | Apples |
+----+--------+-------+---------+
我已经看了不同的连接,以及联合和交叉。但是,我担心这些解决方案不会考虑到重复行的数量。例如,对于这个例子,我希望他们只添加"Mrs Alice apple "
你可以尝试这样做:
INSERT INTO TableB
SELECT Distinct prefix,fname,lname
FROM TableA
SELECT DISTINCT语句用于只返回不同的值。
感谢@JohnFx给出的答案
您可以使用左连接获得缺失的行,并使用is null检查不匹配的行
select a.prefix, a.fname, a.lname
from tableA a
left join tableB b on a.prefix = b.prefix
AND a.fname = b.fname
AND a.lname = b.lname
WHERE b.finame is null
可以使用insert select
插入缺失的行insert into tableB (prefix, fname, lname)
select a.prefix, a.fname, a.lname
from tableA a
left join tableB b on a.prefix = b.prefix
AND a.fname = b.fname
AND a.lname = b.lname
WHERE b.finame is null