【问题标题】:Problem with MySQL SUM in Node.js Express Project with EJS带有 EJS 的 Node.js Express 项目中的 MySQL SUM 问题
【发布时间】:2019-05-09 07:11:20
【问题描述】:

我目前正在尝试在我的 Node.js 项目上构建仪表板。为了获得某些值的概述,应该对它们进行总结。我的 SELECT 在我的 MySQL 数据库中工作正常,但如果我将它包含在我的 Node 项目中,那么我将不会得到任何输出。

app.get('/dash', function(req, res, next) {
    connection.query("SELECT SUM(g_speicherplatz), SUM(g_spielzeit), SUM(g_kosten) FROM games", function(error, result, fields) {
        if(error) {
            req.flash('error', error)
            res.render('games/g-dash', {
                data: ''
            })
        } else {
            res.render('games/g-dash', {
                data: result,
            })
        }
    })
})

EJS 输出:

<div class="container">
    <div class="row">
        <% if (data) { 
            console.log("Anzahl Datensätze: " + data.length);
            data.forEach(function(dash){ %>
            <div class="card mb-3">
               <h3 class="card-header">Statistiken</h3>
               <h3><%= dash.g_speicherplatz %></h3>
               <h3><%= dash.g_spielzeit %></h3>
               <h3><%= dash.g_kosten %></h3>
            </div>
        <% }) %>
        <% } %>
    </div>
</div>

我的错误在哪里?

【问题讨论】:

    标签: javascript node.js express ejs


    【解决方案1】:

    您需要为总和分配别名。

        connection.query("SELECT SUM(g_speicherplatz) AS g_speicherplatz, SUM(g_spielzeit) AS g_spielzeit, SUM(g_kosten) AS g_kosten FROM games", function(error, result, fields) {
    
    

    【讨论】:

      【解决方案2】:

      尝试为您的查询添加别名,然后在您的视图中引用它们:

      SELECT
          SUM(g_speicherplatz) AS g_speicherplatz_sum,
          SUM(g_spielzeit) AS g_spielzeit_sum,
          SUM(g_kosten) QS g_kosten_sum
      FROM games;
      

      在视图中:

      <div class="card mb-3">
          <h3 class="card-header">Statistiken</h3>
          <h3><%= dash.g_speicherplatz_sum %></h3>
          <h3><%= dash.g_spielzeit_sum %></h3>
          <h3><%= dash.g_kosten_sum %></h3>
      </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-18
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 2016-10-05
        • 2018-07-01
        相关资源
        最近更新 更多