0

I am new to SQL. I have a database with two tables: users and collections. The table 'users' stores the users of an app while 'collections' stores a collection of items. Each collection is owned by one user.

I need to get a JSON object with the collections and their owner.

For example:

[
{
  "collection_id": 23,
  "collection_name": "The Beatles Albums"
  "owner": {
      "user_id": 5,
      "first_name": "John",
      "last_name": "Doe"
   }
}
]

This is what I tried:

router.get('/collections/', (req, res) => {
    mysqlconnection.query('SELECT * FROM collections INNER JOIN users ON collections.OwnerID = users.id WHERE collections.OwnerID = users.id ', (err, rows, fields) => {
        if(!err) {
            res.json(rows);
        } else {
            console.log(err);
        }
    })
})

This is what I'm getting:

[
{
  "collection_id": 23,
  "collection_name": "The Beatles Albums",
  "owner": 5,
  "user_id": 5,
  "first_name": "John",
  "last_name": "Doe"
}
]

I'm new to SQL. Any help is greatly appreciated.

matt.c
  • 3
  • 1

1 Answers1

0

I believe that MYSQL JSON_OBJECT fix your problem. Try change your query for this:

SELECT 
  JSON_ARRAYAGG(
    JSON_OBJECT(
      'collection_id', collections.collection_id, 
      'collection_name', collections.collection_name,
      'owner', JSON_OBJECT(
          'user_id', users.user_id, 
          'first_name', users.first_name, 
          'last_name', users.last_name
      )
    )
  ) 
FROM 
  collections 

INNER JOIN 
  users 

ON collections.OwnerID = users.id 

WHERE collections.OwnerID = users.id '
Cássio Lacerda
  • 1,554
  • 1
  • 12
  • 14
  • Thanks a lot for your answer, that SQL query outputs a nested JSON. However, I'm having trouble getting it properly in the response of the request. This is what I get in the console: `JSON_OBJECT('collection_id', collections.ID, 'collection_name', collections.Name, 'owner', JSON_OBJECT('first_name', users.first_name, 'last_name', users.last_name, 'email', users.email, 'location', users.location)): "{"owner": {"email": "joes@gmail.com", "location": "Boston, USA", "last_name": "Doe", "first_name": "John"}, "collection_id": 1, "collection_name": "Lorem ipsum"}"` Any ideas? – matt.c Apr 19 '20 at 02:00