简体   繁体   中英

How can I join a table from two keys referencing same table with SQL Server?

I have a currency table (contains a list of all world currencies), then a currencyConversion table which has a sourceCurrency and targetCurrency (both ints matching the IDs in the currency table.

The currency table also has a 'code' field, which is what makes sense to users, eg USD.

I would like to join the tables but cannot see how as when I join the currencyConversion's source and target currency IDs to the currency table, it excludes everything as there is no match where source AND target are the same.

My SQL for this join is;

SELECT currencyConversion.rate, currencyConversion.sourceCurrencyID, dbo.currencyConversion.targetCurrencyID
FROM currencyConversion INNER JOIN
currency ON dbo.currencyConversion.sourceCurrencyID = currency.id AND currencyConversion.targetCurrencyID = currency.id

I know I could do sub selects but wondered if there was a more efficient solution.

Thanks,

Nick

SELECT cc.rate, cc.sourceCurrencyID , cc.targetCurrencyID, 
                src.code AS 'SourceCurrencyCode', tgt.code AS 'TargetCurrencyCode'
FROM currencyConversion cc
 INNER JOIN currency src ON cc.sourceCurrencyID = src.id 
 INNER JOIN currency tgt ON cc.targetCurrencyID = tgt.id 

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