/    Sign up×
Community /Pin to ProfileBookmark

Using SQL join with id in two fields

Hello,

Table name: currencies
id —- currency
id: 1 => USD
id: 2 => EURO
id: 3 => TL

Table name: exchange
id —- from_unit (Table id “currency”) —- to_unit (Table id “currency”)
1 —- 1 —- 3
2 —- 2 —- 3
3 —- 2 —- 1

Print
USD => TL
EURO => TL
EURO => USD

“`
$exchange = $PDO->prepare(“SELECT
exchange.id,
exchange.from_unit,
exchange.to_unit
currencies.currency,
FROM exchange
INNER JOIN currencies ON exchange.from_unit = currencies.id
ORDER BY ID DESC”);
$exchange->execute();

while ($row = $exchange->fetch()) {
echo $row[‘currency’].”=>”.$row[‘to_unit’];
}
“`

How can I show the “to_unit” field

Thank you from now

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 21.2020 — It is not clear to me what the problem is. Is your echo not displaying anything at all, or the wrong data, or what?
Copy linkTweet thisAlerts:
@gecekuleauthorNov 21.2020 — Currency names are available in a table

In two columns of the other table, the IDs of the currency names are present.

I write the ID in the first "**from_unit**" column and the currency name in the JOIN below. No problem.

INNER JOIN currencies ON exchange.**from_unit** = currencies.id

How do I print the currency name with the "**to_unit**" ID in the second column?

INNER JOIN currencies ON exchange.**to_unit** = currencies.id

Would there be two inner joins?
Copy linkTweet thisAlerts:
@NogDogNov 21.2020 — Sure, you could do:
<i>
</i>SELECT
exchange.id,
exchange.from_unit,
exchange.to_unit,
c1.currency as from_currency,
c2.currency as to_currency
FROM exchange
INNER JOIN currencies c1 ON exchange.from_unit = c1.id
INNER JOIN currencies c2 ON exchange.to_unit = c2.id
Copy linkTweet thisAlerts:
@gecekuleauthorNov 21.2020 — Thank you so much

Problem solved
×

Success!

Help @gecekule spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...