繁体   English   中英

如何在Javascript调用中将SQL字段名称返回给API?

How to Return SQL FIeld Names in Javascript call to API?

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文繁体   英文版本   中英对照 版本,有任何建议请联系yoyou2525@163.com。

我使用Express,Cors和Node组合了一个用于本地mysql数据库的API,现在正尝试提取数据。 我有一个查询,我在其中构造了一个常量以提取一系列统计信息,但是我无法弄清楚如何最好地提取数据,以便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 trucks
app.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 个回复

使用此查询以接收此输出: {"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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题
 
粤ICP备18138465号  © 2020-2022 STACKOOM.COM