-1

作为问题,如何实现目标?例如:

表格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
4

2 回答 2

0

LEFT JOIN这两个表table1table2从第二个表中获取那些不匹配的行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;

SQL 小提琴演示


编辑:

您需要使用UPDATEwithJOIN来执行此操作。就像是:

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;

更新的 SQL Fiddle 演示

这将使您的表格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) |
于 2013-03-26T06:53:33.300 回答
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
于 2013-03-26T06:54:34.053 回答