mysql对列表中不同的元素进行计数

vc9ivgsu  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(306)

在配方表中,我有不同的配料。

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;

最终结果应该是AllingCredit:6和have:2(数据库(小提琴链接)

sycxhyv7

sycxhyv71#

在您的数据中有2个123和403,如果您只想计算它们一次,您应该使用该查询

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
dzhpxtsq

dzhpxtsq2#

我准备了一个解决方案,但有人能检查一下这是不是最快的解决方案。检查这里的小提琴。

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;

相关问题