我使用过这个 chart 库,但我不知道如何将数据加载到其中。我从未将数据从 mysql 加载到图表。所以我不知道什么是最佳实践......
所以我在 MySQL 表中有如下订单行:
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']
的日期数组,我需要每个日期,其中示例 kind=1 的行数。但我不知道 MySQL 查询必须是什么样子...我是否需要查询日期数组中的每个日期?
或者有更好的方法吗?
谢谢你的帮助!
最佳答案
首先,您需要从服务器上的表中提取数据并将其放入浏览器中的 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);
那应该做吗?
关于javascript - 通过sequelize js从mysql数据库加载数据到图表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27899364/