4

I'm making a pretty simple RIGHT JOIN query, but I can't format the output correctly.

Here is the Query:

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);
});

This is the output I have:

[ { 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',
   } ]

And this is the ouput I would like to have:

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

I tried nestTables as you can see,

3
  • You need to loop through the result and built you custom json structure. Commented Apr 2, 2015 at 11:59
  • Are you sure there aren't any formatted output options? Commented Apr 2, 2015 at 12:00
  • As Far as I know with express and mysql connect the result that you are getting is a standard one, where the data is represented with key:val format. Now you need to customize the result as per your need, or check if there is some middle ware or helper module available for this. Commented Apr 2, 2015 at 12:22

1 Answer 1

7

Wrapped for legibility:

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Works for me. Thanks a lot dude. You're a time saver.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.