当我尝试计算喜欢的数量而不是它显示配方中使用的成分的数量

时间:2017-04-17 11:44:30

标签: mysql sql database laravel

这是我的mysql查询

  SELECT r.RECIPE_ID as recipe_id,
    r.RECIPE_NAME as recipe_name,
    r.RECIPE_DESC as recipe_desc,
    r.RECIPE_DURATION duration,
    group_concat(i.ING_NAME separator ', ') as recipe_ingredients,
    rc.CUSINE_NAME as cusine,
    rt.RECIPE_TYPE_NAME as type,
    r.image ,
    count(lr.likecount)
    FROM RECIPE_LIST r 
    inner join likerecipes lr on r.recipe_id = lr.recipe_id
    inner JOIN RECIPE_INGLIST ri ON r.RECIPE_ID = ri.recipe_id 
    inner JOIN ING_LIST i ON ri.ING_ID = i.ING_id and r.RECIPE_ID = ri.recipe_id 
    inner JOIN RECIPE_CUSINE rc ON r.RECIPE_CUSINE_ID = rc.CUSINE_ID 
    inner JOIN RECIPE_TYPE rt ON r.RECIPE_TYPE_ID = rt.recipe_typeid 
    WHERE r.RECIPE_ID >= 1 
    GROUP BY r.RECIPE_NAME

输出表格如下所示 Image1

但是当我删除配料字段及其所有连接并执行相同的查询

SELECT r.RECIPE_ID as recipe_id,
r.RECIPE_NAME as recipe_name,
r.RECIPE_DESC as recipe_desc,
r.RECIPE_DURATION duration,
rc.CUSINE_NAME as cusine,
rt.RECIPE_TYPE_NAME as type,
r.image ,
count(lr.likecount)
FROM RECIPE_LIST r 
inner join likerecipes lr on r.recipe_id = lr.recipe_id
inner JOIN RECIPE_CUSINE rc ON r.RECIPE_CUSINE_ID = rc.CUSINE_ID 
inner JOIN RECIPE_TYPE rt ON r.RECIPE_TYPE_ID = rt.recipe_typeid 
WHERE r.RECIPE_ID >= 1 
GROUP BY r.RECIPE_NAME

我得到了理想的结果 - > Image 2

有什么方法可以显示适量的喜欢和配料。 (PS。我知道第一个查询显示的是成分而不是喜欢,因为当我推断出其中一个成分相同数量减少时。显示的食谱也通过数据透视表recipe_inglist显示加入recipe_list和ing_list表(如果是与它有任何关系))

1 个答案:

答案 0 :(得分:0)

在执行其余连接之前聚合喜欢的内容:

FROM RECIPE_LIST r JOIN
     (SELECT lr.recipe_id, COUNT(*) as likes
      FROM likerecipes lr
      GROUP BY lr.recipe_id
     ) lr
     ON r.recipe_id = lr.recipe_id . . .