简体   繁体   中英

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 (STID) 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM