Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL JOIN to replace IDs with value from another table

Tags:

mysql

Say I have an Encoding table that containing various types, for ex:

    ID  EncodingName
    ------------------
    1   UTF-8
    2   ISO-8859-1

And another EncodingMapping that uses these IDs to keep track of which encodings to convert From and To:

    ID  ItemId_FK  EncodingFromId_FK  EncodingToId_FK
    -------------------------------------------------
    1   45         2                  1  
    2   78         1                  2

I want to create an SQL statement that creates the following result when ItemId_FK = 45 (for example):

   FromEncoding  ToEncoding
   -------------------------
   ISO-8859-1    UTF-8

Seems like it would be simple enough, but I cannot a get a JOIN to work by returning a single row in this format.

What I have so far (THIS IS WRONG):

   SELECT EncodingName As FromEncoding, EncodingName As ToEncoding
   FROM Encoding
   LEFT JOIN EncodingMapping As em
   ON Encoding.ID = em.EncodingFromId_FK OR Encoding.ID = em.EncodingToId_FK
   WHERE ItemId_FK = 45
like image 436
http203 Avatar asked Sep 14 '12 20:09

http203


1 Answers

Close, but not cigar:

SELECT 
  FromEnc.EncodingName AS FromEncoding, 
  ToEnc.EncodingName AS ToEncoding
FROM EncodingMapping
INNER JOIN Encoding AS FromEnc
  ON FromEnc.ID=EncodingMapping.EncodingFromId_FK
INNER JOIN Encoding AS ToEnc
  ON ToEnc.ID=EncodingMapping.EncodingToId_FK
WHERE EncodingMapping.ItemId_FK = 45
like image 199
Eugen Rieck Avatar answered Sep 27 '22 17:09

Eugen Rieck