MySQL同时从多个表中进行SELECT查询

标签 mysql select inner-join

我的数据库中有这样的架构: enter image description here

我想显示特定用户(使用 unique_id 给出)已添加到他的收藏夹中的所有食谱(具有特定字段),这些食谱在表收藏夹(2 个字段 - 用户 ID 和喜欢的食谱)中描述。我不知道该怎么做。

f.e.如果用户喜欢 5 个食谱,该信息将包含在最喜欢的表中(他的 ID 和他喜欢的食谱 ID)。我想显示字段:

  • 食谱。unique_id,
  • 食谱。标题,
  • 食谱。img_tumbnail_link,
  • 食谱。add_date,
  • 食谱。kitchen_type,
  • 食谱。meal_type,
  • 用户。姓名,
  • 用户。姓氏
  • COUNT(喜欢recipe_unique_id_fk) AS like_count

我尝试用这个做一些查询:

SELECT recipe.`unique_id`, recipe.`title`, recipe.`img_tumbnail_link`, recipe.`add_date`, recipe.`kitchen_type`, recipe.`meal_type`, user.`name`, user.`surname`, COUNT(`like`.`recipe_unique_id_fk`) AS like_count 
FROM `recipe` 
JOIN `favourite` ON (recipe.`unique_id` = `favourite`.`recipe_unique_id_fk`) 
JOIN `like` ON (recipe.`unique_id` = `like`.`recipe_unique_id_fk`) 
JOIN `user` ON (recipe.`user_unique_id_fk` = user.`unique_id`)
WHERE favourite.`user_unique_id_fk` = '565096811c0b51.08471830' 
ORDER BY recipe.`add_date` DESC

来自这样的表:

enter image description here

通过此查询,我只收到 1 行而不是 3 行,我应该为 ID 为:565096811c0b51.08471830 的用户获取。有什么帮助吗?谢谢。

我添加了食谱表和结果:)

enter image description here

这是我的查询结果:

enter image description here

以下是所有记录(无重复):http://postimg.org/image/ejjemnozb/

最佳答案

您还使用了与like表的连接,该表只有一行,这就是为什么只返回一行的原因。您可以使用子查询来计算点赞数。我在下面提到了正确的查询:

SELECT recipe.`unique_id`, recipe.`title`, recipe.`img_tumbnail_link`, recipe.`add_date`, recipe.`kitchen_type`, recipe.`meal_type`, user.`name`, user.`surname`, 
(SELECT count(*) from `like` WHERE recipe.`unique_id` = `like`.`recipe_unique_id_fk`) AS like_count
FROM `recipe` 
JOIN `favourite` ON (recipe.`unique_id` = `favourite`.`recipe_unique_id_fk`) 
JOIN `user` ON (recipe.`user_unique_id_fk` = user.`unique_id`)
WHERE favourite.`user_unique_id_fk` = '565096811c0b51.08471830' 
ORDER BY recipe.`add_date` DESC

关于MySQL同时从多个表中进行SELECT查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33966369/

相关文章:

javascript - 在 select2 插件中设置要选择的最小值

mysql - Select * from 'many to many' SQL 关系

javascript - 使用 len 和 setter 续写密码验证失败

mysql - 如何选择静态值列?

php - 从使用 ISODate 保存的 mongodb 数据库获取时间戳

c++ - 检查哪个套接字首先回答 C++

mysql - 使用来自不同表的时间戳对 MySQL 表进行排序

mysql - 从多个表的 INNER JOINS 获取所有记录

javascript - PHP laravel 使用 jQuery 解析数据或将它们组合成单个数组

php - 访问一个表中不属于其他两个表的数据