如何编写需要翻译两列的SQL查询?

时间:2013-01-10 15:48:45

标签: mysql join

我有两张桌子 - 一张有库存记录,另一张有翻译(法国和德国用户)。

库存:

╔════╦═══════╦═══════════════════╦═══════════════════════════╗
║ ID ║ PRICE ║ ITEMTRANSLATIONID ║ ITEMCATEGORYTRANSLATIONID ║
╠════╬═══════╬═══════════════════╬═══════════════════════════╣
║  1 ║    10 ║               423 ║                      1323 ║
║  2 ║    31 ║              1776 ║                      1953 ║
╚════╩═══════╩═══════════════════╩═══════════════════════════╝

文:

╔══════╦═══════════╦════════════╦═════════╗
║  ID  ║  ENGLISH  ║   FRENCH   ║ GERMAN  ║
╠══════╬═══════════╬════════════╬═════════╣
║    1 ║ knife     ║ couteau    ║ messer  ║
║    2 ║ fork      ║ fourchette ║ gabel   ║
║  423 ║ spoon     ║ cuillère   ║ löffel  ║
║ 1323 ║ cultery   ║ couverts   ║ besteck ║
║ 1776 ║ table     ║ table      ║ tabelle ║
║ 1953 ║ furniture ║ meubles    ║ möbel   ║
╚══════╩═══════════╩════════════╩═════════╝

有没有办法编写SQL查询来获取每个股票项目的价格和翻译名称?我一次只需要一种语言。

如果只需要翻译一列,我可以使用INNER JOIN。问题是,有两列需要翻译 - 一列用于项目名称,另一列用于项目类别名称。

即。 要求的输出(法文)

╔════╦═══════╦══════════╦══════════════╗
║ ID ║ PRICE ║   ITEM   ║ ITEMCATEGORY ║
╠════╬═══════╬══════════╬══════════════╣
║  1 ║    10 ║ cuillère ║ couverts     ║
║  2 ║    31 ║ table    ║ meubles      ║
╚════╩═══════╩══════════╩══════════════╝

3 个答案:

答案 0 :(得分:2)

在表Translations上两次加入表Stock,这样您就可以获得表Stock中每列的值

SELECT  a.ID, a.Price, b.French AS Item, c.French AS ItemCategory  
FROM    Stock a
        INNER JOIN Translations b
            ON a.ItemTranslationId = b.ID
        INNER JOIN Translations c
            ON a.ItemCategoryTranslationId = c.ID

答案 1 :(得分:1)

使用此表格结构,您需要JOINTranslations表两次...一次获取Item,然后再次获取ItemCategory

SELECT
    s.ID,
    s.Price,
    i.French AS Item,
    ic.French AS ItemCategory
FROM
    Stock s
    JOIN Translations i ON i.ID = s.ItemTranslationId
    JOIN Translations ic ON ic.ID = s.ItemCategoryTranslationId 

答案 2 :(得分:0)

您可以使用此查询:

SELECT  a.ID, a.Price,
(select French from  Translations b where b.ID=a.ItemTranslationId) as ITEM,
(select French from  Translations c where c.ID=a.ItemCategoryTranslationId) as ITEMCATEGORY
FROM Stock a