mysql连接3个表,多个列排除一个表的结果

z31licg0  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(265)

我正在尝试连接mysql中的3个表,需要一些帮助。
我的第一张table是食谱清单。


**recipes**

RecipeID | RecipeName
1        | Cheese and Ham Toasty
2        | 20 Minute Pasta
3        | Minute Steak

第二个表是分配给recipes表的配料列表


**ingredients**

RecipeID | IngredientID | IngredientName
1        | 1            | Cheese
1        | 2            | Bread
1        | 3            | Ham
1        | 4            | Butter
2        | 5            | Pasta
2        | 6            | Mince
2        | 1            | Cheese
3        | 8            | Steak
3        | 9            | BBQ Sauce

第三个表是一个表,用户可以使用它添加他们不想看到的配料,目前用户只需添加一种配料


**usersList**

IngredientID | userID
1            | 2

我加入表格时的结果如下:


**recipes**

RecipeID | RecipeName
3        | Minute Steak

然而,我的结果要么是所有我不想要的食谱,要么是一个空的结果。下面是我正在使用的mysql,它提供了我不想要的所有菜谱。

SELECT RecipeID, RecipeName FROM recipes LEFT JOIN ingredients
INNER JOIN usersList ON ingredients.IngredientID = usersList.IngredientID 
ON recipes.RecipeID = ingredients.RecipeID
WHERE recipes.RecipeID IS NOT NULL
AND usersList.userID = 2
GROUP BY recipes.RecipeID

如何联接这些表,以便获得所有配方,这些配方不包括用户列表中包含成分的任何配方,并且在用户没有列出成分的情况下仍然提供结果?谢谢你的帮助。

toiithl6

toiithl61#

您也可以在此处使用左连接,如下所示:

select r.RecipeID, r.RecipeName from recipes r
left join (select RecipeID from ingredients i
          join  usersList u on u.RecipeID = i.RecipeID) as u
          on u.RecipeID = r.RecipeID
where u.RecipeID is null
xytpbqjk

xytpbqjk2#

在配方和配料之间使用内部联接,在配料和用户列表之间使用左联接,然后在排除结果中,从用户列表返回的主键不为null。
这个输出将包括多个条目的配方与多种成分-这可能需要整理。。。。

SELECT recipename, GROUP_CONCAT(ingredient_name), 
  SUM(IF(userlist.ingredientid IS NULL, 0, 1))
FROM recipes
INNER JOIN ingredients
ON recipes.recipeid=ingredients.ingredientid
LEFT JOIN userlist
ON ingredients.ingredientid=userlist.ingredientid
AND userlist.userid=_______
GROUP BY recipename
HAVING SUM(IF(userlist.ingredientid IS NULL, 0, 1))=0
n53p2ov0

n53p2ov03#

你不是在寻求加入。你想看看没有特定成分的配方。因此,从配方表中选择并使用 NOT EXISTS 或者 NOT INWHERE 条款。这里有两个简单的解决方案 IN 条款:

select *
from recipes
where recipeid not in
(
  select recipeid
  from ingredients
  where ingredientid in
  (
    select ingredientid 
    from userslist
    where userid = 2
  )
);

相关问题