Nodejs JOIN查询:格式化JSON输出

时间:2015-04-02 11:57:08

标签: mysql json node.js

我正在制作一个非常简单的RIGHT JOIN查询,但我无法正确格式化输出。

以下是查询:

connection.query({sql : "SELECT users.*, rides.* FROM users RIGHT JOIN rides ON users.id = rides.id_user WHERE users.id = ?", nestTables: '_', values : [id] }, function(err, rows){
   console.log(rows);
});

这是我的输出:

[ { users_id: 52,
    users_firstname: 'greg', //End first table data
    rides_latitude: '50.847454', //Second table data: row 1
    rides_longitude: '4.358356',
  },
  { users_id: 52,
    users_firstname: 'greg', //Exactly the same first table data
    rides_latitude: '50.9', //Second table data: row 2
    rides_longitude: '4.4',
   } ]

这是我想要的产品:

[ { users_id: 52,
    users_firstname: 'greg',
    rides : [
         {
         rides_latitude: '50.847454',
         rides_longitude: '4.358356'
         },
         {
         rides_latitude: '50.9',
         rides_longitude: '4.4'
         }
   ]
  }]

我试过nestTables,你可以看到,

1 个答案:

答案 0 :(得分:3)

包装易读:

connection.query({
    sql : "SELECT \
              users.users_id, \
              users.users_firstname, \
              rides.rides_latitude, \
              rides.rides_longitude \
           FROM \
              users \
              RIGHT JOIN rides ON users.id = rides.id_user \
           WHERE \
              users.id = ?", 
    nestTables: '_', 
    values : [id]
}, function (err, rows) {
    var result = [], index = {};

    if (err) throw err;

    rows.forEach(function (row) {
        if ( !(row.users_id in index) ) {
            index[row.users_id] = {
                users_id: row.users_id,
                users_firstname: row.users_firstname,
                rides: []
            };
            result.push(index[row.users_id]);
        }
        index[row.users_id].rides.push({
            rides_latitude: row.rides_latitude,
            rides_longitude: row.rides_longitude
        });
    });

    console.log(result);
});