gpt4 book ai didi

MYSQL 连接列但在不存在的行上返回 NULL

转载 作者:行者123 更新时间:2023-11-29 23:15:41 24 4
gpt4 key购买 nike

我需要一些帮助,因为我无法弄清楚。

我有两张 table

餐 table 食谱列:

ID, Recipe_name, Instructions

表格翻译列:

ID, RecipeID, Translation, Country_ID

我试图实现的是,当用户查找食物食谱并且用户希望以自己的语言(法国或其他语言)查看它时,MYSQL 将向左(或向右)加入翻译文本。如果发现未翻译文本,则应返回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,在本例中为法国

上面的语句返回,因为它似乎是随机翻译的文本,我只需要 13(法国),如果没有翻译的文本,我希望它返回 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 r.* , t.translation 
from recipes r
left join translations t on t.recipeid = r.id and t.country_id = 13
where r.id = 999;

关于MYSQL 连接列但在不存在的行上返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27838944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com