[英]Update column in Table A from Table B where value does not exist in distinct result from Table B in MYSQL
I have two tables both containing a column called domain
.我有两个表都包含一个名为domain
的列。
Table A表 A
|id | domain |
|-------------------|
| 1 | google.com |
| 2 | google.com |
| 3 | yahoo.com |
| 4 | microsoft.com |
| 5 | microsoft.com |
| 6 | slack.com |
| 7 | loom.com |
| 8 | loom.com |
Table B表 B
|id | domain |
|-------------------|
| 1 | google.com |
| 2 | yahoo.com |
| 3 | microsoft.com |
I want to add rows to Table B
for values in Table A
that:我想在Table B
中为Table A
中的值添加行:
Table B
不存在于Table B
Tabel A
在Tabel A
中不同So in the use case above, Table B
would end up like this:所以在上面的用例中, Table B
最终会是这样的:
|id | domain |
|-------------------|
| 1 | google.com |
| 2 | yahoo.com |
| 3 | microsoft.com |
| 4 | slack.com |
| 5 | loom.com |
Here is where I'm at with the query, which doesn't work obviously:这是我在查询的地方,这显然不起作用:
UPDATE tableb tb SET tb.domain = ta.domain WHERE tb.domain NOT IN (SELECT DISTINCT(domain) FROM tablea) ta LIMIT 1
Use exists logic:使用存在逻辑:
INSERT INTO TableB (domain) -- assuming id is auto increment
SELECT DISTINCT domain
FROM TableA a
WHERE NOT EXISTS (SELECT 1 FROM Tableb b WHERE b.domain = a.domain);
The exists clause ensures that the domain from A table does not already exist in the B table. exists 子句确保 A 表中的域在 B 表中不存在。 We select distinct domains from the A table to avoid inserting the same domain more than once.我们 select 从 A 表中区分域以避免多次插入同一个域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.