求助:同表中满足字段匹配条件时更新指定列的SQL写法
Hey there! Let's work through this problem together—you need to update the new_parentID column to match new_campaignID only when old_campaignID equals old_parentID, right? I’ll break down solutions for both common scenarios: SQL databases and Excel spreadsheets, since you mentioned column labels (B/E/F) that fit either use case.
Assuming your table is named something like campaign_data, the correct syntax for a conditional update is straightforward. You’ll use an UPDATE statement with a WHERE clause to target only the rows that meet your matching condition:
UPDATE campaign_data SET new_parentID = new_campaignID WHERE old_campaignID = old_parentID;
Quick Notes on Common Pitfalls:
- If you tried this without the
WHEREclause, you’d update every row in the table—definitely not what you want! TheWHEREfilter ensures only matching rows get modified. - Double-check your column names for typos (case sensitivity matters in some databases like PostgreSQL).
- Make sure you have the necessary
UPDATEpermissions for the table if you’re working in a restricted environment.
If this is data in an Excel sheet (your B/E/F column example makes this likely), you have two easy ways to handle this:
Method 1: Conditional Formula
In the first data row of column F (say, cell F2, assuming row 1 is headers), enter this formula:
=IF(B2=E2, D2, F2)
- This checks if B2 (old_campaignID) equals E2 (old_parentID). If yes, it pulls the value from D2 (new_campaignID); if not, it keeps the original value in F2 (new_parentID).
- Drag the fill handle (the small square at the bottom-right of the cell) down to apply this formula to all rows.
- To convert formulas to static values (so they don’t change if you edit other cells later), select column F, right-click → Copy → right-click again → Paste Special → choose Values.
Method 2: Filter + Batch Fill
- Turn on filters: Select your header row → go to the Data tab → click Filter.
- Filter rows where B equals E: Click the dropdown arrow in column B → Number Filters → Equals → enter
=E1(replace E1 with the header cell of your old_parentID column) → click OK. - In the first visible row of column F, enter
=D2(linking to the new_campaignID cell in that row) and drag the fill handle down to cover all filtered rows. - Turn off filters, then convert formulas to values as described above.
内容的提问来源于stack exchange,提问作者DavidO

