我正在尝试访问具有restaurant_id = 2的食物的列表,如果carts表中的food_id应该打印cart_id,如果fasest表中的food_id应该打印favorite_id,否则它将返回null。但是我在这里面临的问题是我从那家特定的餐馆得到的food_id,但是在检查购物车和收藏夹ID时却无法检查user_id。

food_id在carts表中,但不适用于该用户,但显示该cart_id。如何使查询正确?

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


SQL查询:

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)

最佳答案

您需要使用以下内容:

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过滤两个表(卡片/收藏夹)

关于mysql - 带多个OR的Where子句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49526355/

10-11 17:07