【问题标题】:Load data into chart through sequelizejs from mysql database通过 sequelizejs 从 mysql 数据库将数据加载到图表中
【发布时间】:2015-01-12 10:01:10
【问题描述】:

我已经使用了这个chart 库,但我不知道如何将数据加载到其中。我从未将数据从 mysql 加载到图表。所以我不知道什么是最佳实践......

所以我在 MySQL 表 Orders 中有如下行:

id | price | kind | orderdate
-----------------------------
1  |  35   | 2    | 2013-01-01
2  |  30   | 1    | 2013-01-01
3  |  25   | 3    | 2013-01-01
4  |  15   | 2    | 2013-01-01

进一步 c3js 以如下格式加载数据:

   columns: [
        ['x', '2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05'],
        ['kind1', 30, 200, 100, 400, 150],
        ['kind2', 30, 200, 100, 400, 150],
        ['kind3', 30, 200, 100, 400, 150],
    ]

所以我创建了如下['x', '2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05'] 的日期数组,并且我需要每个日期,示例种类=1 的行数。 但我不知道 MySQL 查询必须是什么样子......我需要查询日期数组中的每个日期吗? 还是有更好的办法?

感谢您的帮助!

【问题讨论】:

    标签: javascript mysql sequelize.js c3.js


    【解决方案1】:

    首先,您需要从服务器上的表中提取数据并将其导入浏览器上的 javascript。如何做到这一点取决于您使用的是什么,例如PHP,但查询可能是这样的:

    select   orderdate, kind, sum(price) as total
    from     #orders
    where    orderdate between '1 Jan 2013' and '10 jan 2013'
    group by orderdate, kind
    

    我的偏好是通过 JSON API 公开数据,这样您就可以以这种格式从 url(用 from & to 日期参数化)获取数据:

    [
    {'orderdate':'2013-01-01', 'kind': 1, 'total': 30},
    {'orderdate':'2013-01-01', 'kind': 2, 'total': 50},
    {'orderdate':'2013-01-01', 'kind': 3, 'total': 25},
    {'orderdate':'2013-01-02', 'kind': 1, 'total': 30},
    {'orderdate':'2013-01-02', 'kind': 2, 'total': 20},
    {'orderdate':'2013-01-02', 'kind': 3, 'total': 23}
    ]
    

    然后将数据“转置”到您需要的列中:

    ['x', '2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04', '2013-01-05'],
    ['kind1', 30, 200, 100, 400, 150],
    ['kind2', 30, 200, 100, 400, 150],
    ['kind3', 30, 200, 100, 400, 150],
    

    第一列是直截了当的,因为您有从和到日期。

    建立第 2、3、4 行,假设您知道种类列表:

    for each kind:
     create an array, eg: var data = ['kind1'];
     initialise a sum variable, eg: var sum = 0;
     for each date (in the correct order):
      loop through the array, if the date & the kind match, add to the sum variable
     add the sum to the array, eg: data.push(sum);
    

    应该这样吗?

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多