作为问题,如何实现目标? 例如:
表1
place_id place_name Invoice_no
100 Sydney NULL
101 Melbourne NULL
102 Adlaide NULL
103 Gold Coast NULL
104 Perth NULL
105 Hobart NULL
表2
Invoice_id Invoice_no place_id
1 NIT1001 100
2 NIT1002 101
3 NIT1002 102
4 NIT1003 103
目标表
place_id place_name Invoice_no
100 Sydney NIT1001
101 Melbourne NIT1002
102 Adlaide NIT1002
103 Gold Coast NIT1003
104 Perth NULL
105 Hobart NULL
答案 0 :(得分:0)
LEFT JOIN
两个表格table1
和table2
,以invoice_id = NULL
从第二个表中获取那些不匹配的行:
INSERT INTO TargetTable(place_id, place_name, invoice_id)
SELECT
t1.place_id,
t1.place_name,
t2.invoice_id
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON t1.place_id = t2.place_id;
<击> 撞击>
您需要UPDATE
与JOIN
一起使用才能执行此操作。类似的东西:
UPDATE t1
SET t1.Invoice_no = t2.Invoice_no
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.place_id = t2.place_id;
这将使您的表table1
看起来像:
| PLACE_ID | PLACE_NAME | INVOICE_NO |
--------------------------------------
| 100 | Sydney | NIT1001 |
| 101 | Melbourne | NIT1002 |
| 102 | Adlaide | NIT1002 |
| 103 | Gold Coast | NIT1003 |
| 104 | Perth | (null) |
| 105 | Hobart | (null) |
答案 1 :(得分:0)
使用JOIN子句:
INSERT INTO targetTable
SELECT a.place_id, a.place_name, b.invoice_no
FROM table1 a LEFT JOIN table2 b
ON a.place_id = b.place_id