我使用 Express、Cors 和 Node 将本地 mysql 数据库的 API 放在一起,现在正在尝试提取数据。我有一个查询,其中我构建了一个 const 来提取一系列统计数据,但我不知道如何最好地提取数据,以便 json 中的每个元素都具有正确的字段:const express = require('express');const cors = require('cors');const mysql = require('mysql');const app = express();const COUNTS_QUERY = 'SELECT COUNT(*) AS total_stands FROM carts UNION SELECT SUM(current_orders) as total_orders FROM carts UNION SELECT AVG(rating) as rating FROM carts';app.listen(4000, () => { console.log('Server listening on port 4000')});//call query to count trucksapp.get('/stats', (req, res) => { connection.query(COUNTS_QUERY, (err, results) => { if(err) { return res.send(err) } else { console.log(results) return res.json({ data: results }) } })})我收到以下结果:{"data":[{"total_stands":1541},{"total_stands":35218},{"total_stands":2.9792}]}如何取回每个统计数据都有适当字段名称的对象?
1 回答
12345678_0001
TA贡献1802条经验 获得超5个赞
使用此查询以接收此输出: {"data":[{"total_stands":1541},{"total_orders":35218},{"rating":2.9792}]}
SELECT
(SELECT COUNT(*) AS total_stands FROM carts) AS total_stands,
(SELECT SUM(current_orders) as total_orders FROM carts) AS total_orders,
(SELECT AVG(rating) as rating FROM carts) AS rating
添加回答
举报
0/150
提交
取消