2017-02-06 181 views
0

我有以下表格:插入查詢與更新

表 「名稱」:

ID  | Name 
--- | --- 
123 | John 
164 | Peter 
346 | Mark 
679 | Bob 

表 「公司」:

ID  | Company 
--- | --- 
111 | XXX 
666 | YYY 
777 | ZZZ 

表 「表1」:

ID  | c1 | c2 | NameID | CompanyName 
--- | --- | --- | ------ | ----------- 
1254 | 1 |  A |  123  |  XXX 
1548 | 1 |  A |  123  |  YYY 
2649 | 1 |  A |  123  |  ZZZ 
2687 | 3 |  B |  164  |  ZZZ 
2699 | 1 |  A |  164  |  YYY 
2700 | 4 | (NULL) |  346  |  XXX 
2711 | 4 | (NULL) |  346  |  YYY 
2900 | 4 |  A |  679  |  YYY 

我需要做一個插入查詢,使記錄使用相同的c1和c2(如果c2不爲空)或僅相同的c1(如果c2爲null)插入到Table2中,並將Table2中的ID更新爲Table1中的最小ID。

結果應該是這樣的:

表「表2」:

ID  | c1 | c2 | NameID | CompanyID 
--- | --- | --- | ------ | ----------- 
1254 | 1 |  A |  123  |  111 
1254 | 1 |  A |  123  |  666 
1254 | 1 |  A |  123  |  777 
2687 | 3 |  B |  164  |  777 
2687 | 1 |  A |  164  |  666 
2700 | 4 | (NULL) |  346  |  111 
2700 | 4 | (NULL) |  346  |  666 
2900 | 4 |  A |  679  |  666 
+1

,我可以從結果判斷,你只需要更改公司名稱到CompanyID –

+0

我相信你想要創建一個表來存儲選擇的查詢結果,這不是一個好主意,只需在需要時提供查詢即可。更新ID通常也是一個壞主意,您可能會破壞數據的完整性。 – Ruli

+0

@Ruli這只是我需要以最小的ID插入所有記錄。 – Sally

回答

0
INSERT INTO Table2(ID, c1, c2, NameId, CompanyId) 
SELECT 
    minTable.ID AS ID, 
    t1.c1 AS c1, 
    t1.c2 AS c2, 
    t1.NameId AS NameId, 
    c.ID AS CompanyId 
FROM Table1 t1 
JOIN Companies c ON t1.CompanyName = c.Company 
JOIN (
    SELECT 
     MIN(t1.ID) AS ID, 
     t1.c1 AS c1, 
     t1.c2 AS c2 
    FROM Table1 t1 
    JOIN Companies c ON t1.CompanyName = c.Company 
    GROUP BY c1, c2 
) minTable ON t1.c1 = minTable.c1 AND (t1.c2 = minTable.c2 OR (t1.c2 IS NULL AND minTable.c2 IS NULL)) 
+0

ID的最小識別碼也是不同的。這是主要情況。我需要基於c1和c2的最小ID – Sally