【发布时间】:2019-10-29 02:21:00
【问题描述】:
必要的表格
recipe_post
+-----------+-----------+-------+
| recipe_id | posted_by | title |
+-----------+-----------+-------+
friend_request (followers table)
+----------+-----------+
| follower | following |
+----------+-----------+
此查询从 recipe_ingredients 表中获取食材并将其与 users_ingredients 表进行匹配,并返回所有帖子的状态为用户是否可以做饭
SELECT u.uid, ri.recipe_id,
COUNT(ui.i_id) AS available_ingredients, -- Number of ingredients the user has that are required to cook this recipe
COUNT(ri.i_id) AS required_ingredients, -- Number of ingredients that are required to cook this recipe
CASE
WHEN COUNT(ui.i_id) = COUNT(ri.i_id) THEN 'can_cook'
WHEN COUNT(ui.i_id) > 0 THEN 'has_some_ingredients'
ELSE 'has_no_ingredients'
END AS state,
rp.recipe_id,rp.name,rp.description
FROM users u
CROSS JOIN recipe_ingredients ri
LEFT JOIN userIngredients ui ON(ri.i_id = ui.i_id AND u.uid = ui.uid)
INNER JOIN recipe_post rp ON rp.recipe_id = ri.recipe_id
WHERE u.uid = 1 --matching with user 1
GROUP BY u.uid, ri.recipe_id, rp.recipe_id
ORDER BY u.uid, ri.recipe_id;
我创建了另一个查询,它只返回他们关注的用户的帖子
SELECT * FROM recipe_post p
INNER JOIN friend_requests f ON (f.following = p.posted_by)
WHERE f.follower = 5;
我无法将此查询添加到第一个查询,以便它只能显示他们关注的用户的帖子
【问题讨论】:
标签: mysql sql relational-database