猿问

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

我使用 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 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}]}

如何取回每个统计数据都有适当字段名称的对象?


拉风的咖菲猫
浏览 160回答 1
1回答

12345678_0001

使用此查询以接收此输出: {"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
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答