5

假设我有一个包含各种类型的编码表,例如:

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

还有另一个EncodingMapping,它使用这些 ID 来跟踪要转换 From 和 To 的编码:

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

我想创建一个 SQL 语句,当 ItemId_FK = 45(例如)时创建以下结果:

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

似乎它很简单,但我无法通过以这种格式返回单行来让 JOIN 工作。

到目前为止我所拥有的(这是错误的):

   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
4

3 回答 3

8

关闭,但不是雪茄:

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
于 2012-09-14T20:41:23.320 回答
1

您只需要双重加入同一个表:

SELECT from.EncodingName AS FromEncoding,
  to.EncodingName AS ToEncoding
FROM EncodingMapping AS m
LEFT JOIN Encoding AS from ON m.EncodingFromId_FK=from.ID
LEFT JOIN Encoding AS to ON m.EncodingToId_FK=to.ID
WHERE ItemId_FK=45

作为注释,包括_FK简单 ID 列的扩展似乎有点多余。

于 2012-09-14T20:42:16.360 回答
0

你的意思应该有两个连接。一个用于“FromEncoding”,另一个用于“ToEncoding”。

像这样:

Select  FromEncoding.Title
,   ToEncoding.Title
    From    EncodingOrder
    Inner   Join
        Encoding        As  FromEncoding
    On  FromEncoding.Id     =   EncodingOrder.From_Encoding_Id
    Inner   Join
        Encoding        As  ToEncoding
    On  ToEncoding.Id       =   EncodingOrder.To_Encoding_Id

干杯

于 2012-09-14T20:42:33.123 回答