我有一個主要的增量ID列,并且必須根據其他兩列(Condition1和Condition2 )的值來查找并設定其所有子項(在ParentID列中) Started ParentID 始終具有 Condition2 = 1 (并且在 Condition1 列中的值相同)
初始表
---------------------------------------------
| ID | ParentID | Condition1 | Condition2 |
---------------------------------------------
| 1 | null | 1000 | 1 |
| 2 | null | 1000 | null |
| 3 | null | 1000 | null |
| 4 | null | 2000 | 1 |
| 5 | null | 2000 | null |
| 6 | null | 2000 | null |
| 7 | null | 3000 | 1 |
| 8 | null | 3000 | null |
| 9 | null | 3000 | null |
---------------------------------------------
期望的輸出
---------------------------------------------
| ID | ParentID | Condition1 | Condition2 |
---------------------------------------------
| 1 | 1 | 1000 | 1 |
| 2 | 1 | 1000 | null |
| 3 | 1 | 1000 | null |
| 4 | 4 | 2000 | 1 |
| 5 | 4 | 2000 | null |
| 6 | 4 | 2000 | null |
| 7 | 7 | 3000 | 1 |
| 8 | 7 | 3000 | null |
| 9 | 7 | 3000 | null |
---------------------------------------------
當前代碼只為每個新 ID 回傳一行
update u
set u.ParentID = u.ID
from [db].[dbo].[tbl] u
inner join [db].[dbo].[tbl] on
u.Condition2 = 1 and u.Condition1 = u.Condition1
uj5u.com熱心網友回復:
我認為這樣做的一種直觀方法是
UPDATE [db].[dbo].[tbl] u
SET u.ParentID = (SELECT id FROM [db].[dbo].[tbl] u2 WHERE u2.condition1 = u.condition1 and u2.condition2 = 1)
我并不是說這比您嘗試做的更好,只是我認為如果您遇到問題,它非常直觀且易于理解。
我認為您正在尋找的解決方案是:
update u
set u.ParentID = u2.ID
from [db].[dbo].[tbl] u
inner join [db].[dbo].[tbl] u2 on
u2.Condition2 = 1 and u.Condition1 = u2.Condition1
這里的重要區別是我已經為 join-to-self 中的兩個表命名(u 和 u2)。你不想設定u.ParentID = u.ID(如你的問題),你想設定u.ParentID = u2.ID(注意2)。同樣,您不想加入表u.condition1 = u.condition1(因為在此示例中始終如此)或u.condition2 = 1(因為您將該條件應用于您正在更新的表,而不是您加入的表)。即使它是一個自連接,你也需要清楚你參考的是哪個表。u在您的查詢中是指正在更新的表,而不是連接右側的表。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474581.html
