具有多个OR的Where子句

时间:2018-03-28 04:53:14

标签: mysql sql

我试图访问food_id = 2的食物列表,如果carts表中的food_id应该打印cart_id,如果收藏夹表格中的food_id应该打印favorite_id,否则它将返回null。但我面临的问题是food_id我从那个特定的餐馆来,但在检查购物车和收藏夹ID时,它无法检查user_id。

food_id位于购物车表中,但不适用于该用户,但它显示了cart_id。如何使查询正确?

Foods table: id, restaurant_id
Carts Table: id, user_id, food_id
Favorites Table: id, user_id, food_id

SQL QUERY:

SELECT foods.id, carts.id as cart_id , favorites.id as favorite_id 
FROM foods 
LEFT JOIN carts 
ON carts.food_id= foods.id 
LEFT JOIN favorites 
ON favorites.food_id= foods.id 
WHERE foods.restaurant_id = 2 
AND (carts.user_id = 1 OR favorites.user_id = 1)

1 个答案:

答案 0 :(得分:3)

你需要使用这样的东西:

SELECT foods.id, carts.id as cart_id, favorites.id as favorite_id
FROM foods
left join carts on carts.food_id=foods.id and carts.user_id = 1
LEFT JOIN favorites on favorites.food_id=foods.id and favorites.user_id = 1
WHERE foods.restaurant_id = 2

请注意,您需要按用户ID

过滤这两个表(卡片/收藏夹)