假设我有一个包含各种类型的编码表,例如:
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
答案 0 :(得分: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
答案 1 :(得分:0)
你只需要加入同一个表:
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
注意,在简单ID列上包含_FK
扩展名似乎有点多余。
答案 2 :(得分: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
干杯