【问题标题】:mysql count distinct elements which you have in a listmysql计算列表中的不同元素
【发布时间】:2018-06-21 07:22:10
【问题描述】:

在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 和 have: 2. (DB Fiddle link)

【问题讨论】:

    标签: mysql group-by count


    【解决方案1】:

    在您的数据中,您有 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
    

    【讨论】:

    • 不,这也不起作用,检查db-fiddle.com/f/XhZs8yAyvRkubyYCf1GiY/6
    • @Gasper 此查询工作正常,它返回您在帖子中写的结果 allIngredient: 6 and have: 2
    • 是的,如果您尝试使用 123、403 两种成分,结果还可以,但如果您只尝试一种,您也会得到 2,这是错误的,它应该是 1...
    【解决方案2】:

    我准备了一个解决方案,但有人可以检查这是否是最快的解决方案。检查 DB Fiddle here

     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;
    

    【讨论】:

      猜你喜欢
      • 2015-08-19
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多