mysql计算列表中包含的不同元素

时间:2018-06-21 07:22:11

标签: mysql group-by count

在recipie_ingredient表中,我有不同的成分。

create table recipe_ingredient (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    rel_recipe INT(6),
    rel_ingredient INT(6)
  );

INSERT INTO recipe_ingredient (rel_recipe, rel_ingredient) VALUES(1, 32);
INSERT INTO recipe_ingredient (rel_recipe, rel_ingredient) VALUES(1, 99);
INSERT INTO recipe_ingredient (rel_recipe, rel_ingredient) VALUES(1, 123);
INSERT INTO recipe_ingredient (rel_recipe, rel_ingredient) VALUES(1, 123);
INSERT INTO recipe_ingredient (rel_recipe, rel_ingredient) VALUES(1, 227);
INSERT INTO recipe_ingredient (rel_recipe, rel_ingredient) VALUES(1, 395);
INSERT INTO recipe_ingredient (rel_recipe, rel_ingredient) VALUES(1, 403);
INSERT INTO recipe_ingredient (rel_recipe, rel_ingredient) VALUES(1, 403);

根据我的食材,我想获得包含我的食材的食谱。我想在食谱中获得许多独特的成分。在DB Fiddle中,我创建了一个表并插入了演示数据,还添加了当前无法正常运行的SQL。

SELECT
  COUNT(distinct(ri.rel_ingredient)) as allIngredient,
  sum((ri.rel_ingredient) in (123,403)) have
FROM recipe_ingredient ri
GROUP BY ri.rel_recipe;

最终结果应为 allIngredient :6和拥有:2。(DB Fiddle link

2 个答案:

答案 0 :(得分:1)

数据中的成分123和403是2倍,如果只想计算一次,则应使用该查询

SELECT
  COUNT(distinct(ri.rel_ingredient)) as allIngredient,
  COUNT(distinct(ri.rel_ingredient in (123,403))) have
FROM recipe_ingredient ri
GROUP BY ri.rel_recipe

答案 1 :(得分:0)

我准备了一个解决方案,但有人可以检查这是否是最快的解决方案。检查数据库小提琴POSIX standard

 SELECT r.id, r.name, 
    count(temp.rel_ingredients) as allIngredients,
    sum(temp.rel_ingredients in (123,403)) as have,
    (sum(temp.rel_ingredients in (123,403)) / count(temp.rel_ingredients)) as missing_ratio
 FROM (
  SELECT
    distinct(ri.rel_ingredient) as rel_ingredients,
    ri.rel_recipe
  FROM recipe_ingredient ri
) AS temp
LEFT JOIN recipe r ON r.id = temp.rel_recipe
GROUP BY temp.rel_recipe
HAVING have != 0
ORDER BY missing_ratio DESC, allIngredients DESC
LIMIT 0, 10;