【问题标题】:How can I change mysql db query?如何更改 mysql 数据库查询?
【发布时间】:2021-08-20 05:17:21
【问题描述】:

我想在 api 端点接收的数据是:

[
    {"Products":5,"Computer":2,"Handphone":3},
    {"Fruits":4,"Orange":2,"Apple":2},
    {"Consumables":6,"Tissue":2,"Wet Wipes":3, "Handkerchief":1}
]

所以产品类别包含电脑、手机。水果类包括橙子和苹果。消耗品类包括纸巾、湿纸巾和手帕

我在 mySQL 中有以下数据:

ID Items Category
1 Computer Products
2 Handphone Products
3 Computer Products
4 Handphone Products
5 Handphone Products
6 Orange Fruits
7 Orange Fruits
8 Apple Fruits
9 Apple Fruits
10 Tissue Consumables
11 Tissue Consumables
12 Wet Wipes Consumables
13 Wet Wipes Consumables
14 Handkerchief Consumables
15 Wet Wipes Consumables

这是我用来在反应中进行数据库查询的代码:

app.get("/countintents", (req, res) => {
  db.query(
    "SELECT SUM(CASE WHEN intent IN ('Products', 'Land Transport') THEN 1 END) AS products, SUM(CASE WHEN intent IN ('Air Freight', 'Industry Solutions', 'Aerospace and Defense') THEN 1 END) AS industry_solutions, SUM(CASE WHEN intent in ('Profile', 'Contact Us') THEN 1 END) AS about_us FROM data_analytics",
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        res.send(result);
      }
    }
  );
});

我会问我的数据库查询应该是什么?

【问题讨论】:

    标签: javascript mysql sql node.js reactjs


    【解决方案1】:

    您可以在数据库查询中获得组总数,如下所示。

    SELECT category, items, count_items FROM(
            select items, category, count(items) count_items
            from <your_table>
            group by items, category
            UNION ALL
            SELECT Category, Category, Count(category)
            from <your_table>
            GROUP BY Category
        ) X ORDER BY category,count_items.
    

    我正在检查您需要的结果是否支持 Mysql JSON。

    【讨论】:

    • 好的,我在我的问题中添加了列,如果我没有类别列,我还能使用 ALIAS 吗?
    【解决方案2】:

    您可以使用group by with rollup 构造值:

    select category, item, count(*) as cnt
    from t
    group by category, item with rollup
    having category is not null ;
    

    您可以使用字符串聚合构造带有字符串的单独行:

    select group_concat(coalesce(item, category), ':', cnt order by (item is null) desc, item)
    from (select category, item, count(*) as cnt
          from t
          group by category, item with rollup
          having category is not null
         ) ci
    group by category;
    

    或作为 JSON 数组:

    select json_arrayagg(json_object(coalesce(item, category), cnt))
    from (select category, item, count(*) as cnt
          from t
          group by category, item with rollup
          having category is not null
         ) ci
    group by category;
    

    Here 是一个 dbfiddle。

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 1970-01-01
      • 2016-12-09
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多