How do I lookup a value in a table and insert it into another table?
The SQL below selects distinct rows from a table and inserts them into a third table. It works fine.
There is a third column (STI开发者_开发技巧D) that I want to insert into the destination table. In the SourceData table, there is a column name STFP. I need to lookup the value of STFP in a third table, STS table, and get the value of STID. How do I get the value of STID?
INSERT INTO DestinationTable(CTYFP, CTYNAME)
SELECT DISTINCT CTYFP , CTYNAME
FROM SourceData
Just join to the other table:
INSERT INTO DestinationTable (CTYFP, CTYNAME, STFP)
SELECT DISTINCT sd.CTYFP, sd.CTYNAME, STS.STFP
FROM SourceData sd
JOIN STS on SIS.STID = sd.STID;
Note: Your question did not post table column names, so I have guessed. You may have to adjust to suit your actual column names.
If I'm understanding you, this should work:
INSERT INTO DestinationTable(CTYFP, CTYNAME, STID)
SELECT DISTINCT SourceData.CTYFP , SourceData.CTYNAME, STS.STID
FROM SourceData
INNER JOIN STS ON SourceData.STFP = STS.STFP
INSERT INTO DestinationTable(CTYFP, CTYNAME, STFP)
SELECT DISTINCT CTYFP , CTYNAME, STFP
FROM SourceData INNER JOIN ThirdTable on SourceData.Id = ThirdTable.SomeKey
精彩评论