Update SQL by joining 3 tables

雨燕双飞 提交于 2019-12-25 04:45:09

问题


Using the below table structure i need to insert the Line ID into the approved table, using the location name as the lookup value. How do i go about doing this?

I started off using the below code, but it doesn't do much. Not that great on SQL joins so any help is much appreciated.

UPDATE dbo.Approved 
SET dbo.Approved.Groupid=dbo.Lines.ID 
FROM dbo.Lines,dbo.Approved, dbo.Locations 
WHERE dbo.Approved.Location = dbo.Locations.Location_Name

Approved

ID (PK) | Incident             | Location     | GroupID
--------------------------------------------------------
1       | Theft of luggage     |Oxford Circus | Null
2       | Theft of bag         |Kings Cross   | Null

Lines

ID (PK) | Line_Name      | 
--------------------------
1       | Central        |
2       | Northern       |
3       | Circle         |

Locations

ID (PK) | Location_Name  | LineID
---------------------------------
1       | Oxford Circus  |1
2       | Kings Cross    |2
3       | Victoria       |3

回答1:


This is what I would suggest you :

UPDATE t1.Approved
SET t1.Groupid = t2.ID
FROM dbo.Approved t1
INNER JOIN dbo.Locations t2 ON t1.Location = t2.Location_Name

You don't need the Lines table because what you want to insert, at the end is just the LineID not the Line_Name.

Hope it could help,



来源:https://stackoverflow.com/questions/4410010/update-sql-by-joining-3-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!