使用nodejs来查询mysql数据库

我使用mysql模块nodejs-mysql我有两个表,他们的结构是这样的:

表刻

id |nick | -------------- 1 |Arnold | 2 |Bob | 

表顺序

 nick |money | --------------- Arnold |12 | Arnold |43 | Arnold |3 | Bob |32 | Bob |2 | 

我想要一个JSON对象的结构是这样的:

 [ {id:1, nick:'Arnold', order:[{money:12},{money:43},{money:3}]}, {id:2, nick:'Bob', order[{money:32},{money:2}]} ] 

所以我该怎么做?我使用nodejs

我有什么尝试:

  var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'example.org', db : 'db' user : 'user', password : 'secret' }); connection.connect(); connection.query('select * from nicks',function(err,data){ //here I travese the data array,and select the order table to get the money filed data. }); 

我知道如何用node.js创build一个查询,我只是不知道一个方法来获得我想要的结果。我不知道如何做出正确的查询。

这是另一个解决scheme:

 var mysql = require('mysql'); var conn = mysql.createConnection({ host : 'localhost', database : 'test', }); var query = ' \ SELECT id, nicks.nick, GROUP_CONCAT(money) AS money \ FROM nicks, orders \ WHERE orders.nick = nicks.nick \ GROUP BY id'; conn.query(query, function(err, rows, fields) { rows.forEach(function(row) { row.order = row.money.toString().split(',').map(function(value) { return { money : Number(value) }; }); delete row.money; }); // as an example, we'll print the object as JSON console.log(JSON.stringify(rows, null, 2)); }); 

请按照https://github.com/felixge/node-mysql上的文档您需要设置一个连接并查询数据库

 var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'example.org', user : 'bob', password : 'secret' }); var queryString = "SELECT * FROM nicks n JOIN order o ON n.nick=o.nick"; connection.query(queryString, function(err, rows) { var outputJSON = []; for row in rows{ outputJSON.push(row); } return outputJSON.toJSON() }); 

你需要实现的functionJSON格式化您的输出,只select所需的字段,你需要你JSON