sql >> Base de Datos >  >> RDS >> Mysql

Nodejs JOIN consulta:formato de salida JSON

Envuelto para legibilidad:

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