![](/img/trans.png)
[英]Update one mysql table from another where third table matches old id to new id
[英]Update column from one table to another only if the id matches on 2 tables and not the third
我有3張桌子ABC。
|--------A-------|
| ID | Price |
|------|---------|
| 1 | 0 |
|----------------|
| 2 | 0 |
|------|---------|
| 3 | 0 |
|----------------|
| 4 | 0 |
|----------------|
|--------B-------|
| ID | Price |
|------|---------|
| 1 | 2.00 |
|----------------|
| 2 | 5.00 |
|------|---------|
| 3 | 3.00 |
|----------------|
| 4 | 1.00 |
|----------------|
|--------C-------|
| ID | Price |
|------|---------|
| 5 | 2.00 |
|----------------|
| 6 | 5.00 |
|------|---------|
| 1 | 2.00 |
|----------------|
| 2 | 5.00 |
|----------------|
我只想在B.ID不存在於C.ID中的情況下才將B.price復制到A.price。 在這種情況下,它將是A.ID(3加4)。 結果應該看起來像這樣
|--------A-------|
| ID | Price |
|------|---------|
| 1 | 0 |
|----------------|
| 2 | 0 |
|------|---------|
| 3 | 3.00 |
|----------------|
| 4 | 1.00 |
|----------------|
使用更新聯接。 下面的查詢在A和B表之間進行內部聯接,因為此處的匹配是進行更新所必需的。 然后,使用WHERE
子句限制B表和C表之間的匹配,然后再向左WHERE
C表。
UPDATE A a
INNER JOIN B b
ON a.ID = b.ID
LEFT JOIN C c
ON b.ID = c.ID
SET a.Price = b.Price
WHERE c.ID IS NULL;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.