MYSQL 加入列但 return 在不存在的行上为 NULL

MYSQL Join column but return NULL on not existent row

我需要一点帮助,因为我想不通。

我有两张桌子

餐桌食谱 列数:

ID, Recipe_name, Instructions

表格翻译 列数:

ID, RecipeID, Translation, Country_ID

我试图实现的是当用户查找食物食谱并且用户希望使用自己的语言(法国或其他语言)时 MYSQL 将左(或右)加入翻译文本.如果没有找到 NO TRANSLATED 文本,它应该 return NULL

我试过这个:

SELECT Recipes.* , Translations.Translation FROM Recipes
INNER JOIN Translations.Translation
ON Recipes.ID = Translations.RecipeID
WHERE Recipes.ID = 999 AND COALESCE(Translations.Country_ID, '') != '13'
Limit 1

Recipes.ID = 999 <-是存储在数据库中的配方 Translations.Translation = 13 <- 国家 ID,在本例中为法国

上面的语句returns好像是随机翻译回来的文字,我只需要13(法国),如果没有翻译文字,我希望它return NULL。

提前致谢。

编辑 -- 有表格:

**Table Recipes

    |ID |  Recipe_name | Instructions
    ----+--------------+-------------
    | 1 | Tasty Dish   | 1 spoon of sugar
    | 2 | Chicken      | 1 chicken

    ** Table Translations

    |ID |  Recipe_ID | Translation         | Country_ID
    ----+------------+---------------------+-----------
    | 1 |      1     | 1 cuillère de sucre |     13  (france)
    | 2 |      1     | 1 Lepel Suiker      |     11  (dutch)

没有法语翻译的另一种情况:

**Table Recipes

    |ID |  Recipe_name | Instructions
    ----+--------------+-------------
    | 1 | Tasty Dish   | 1 spoon of sugar
    | 2 | Chicken      | 1 chicken

    ** Table Translations

    |ID |  Recipe_ID | Translation         | Country_ID
    ----+------------+---------------------+-----------
    | 2 |      1     | 1 Lepel Suiker      |     11  (dutch)

MYSQL 仍应添加列 TRANSLATION 但填充为 NULL

尝试左连接。

SELECT Recipes.* , Translations.Translation FROM Recipes
LEFT JOIN Translations
ON Recipes.ID = Translations.RecipeID AND COALESCE(Translations.Translation, '') != '13'
WHERE Recipes.ID = 999 
Limit 1

您的查询似乎有点混乱。你说你想使用外连接(左或右),但你使用了内连接。只需使用外连接,查询就很简单:

select r.* , t.translation 
from recipes r
left join translations t on t.recipeid = r.id and t.country_id = 13
where r.id = 999;