0

Suppose we have these 2 following tables:

reservations table: id, time, user_id

users table: id, name

When selecting reservations, how can I get the following output on pure MySQL without querying for the "user" manually on php for each reservation?

Because it gets really slow when looping through thousands of reservations.

{
 id: 1,
 time: "123456789",
 user_id: 321,
 user: {
        id: 321,
        name: John Doe
       }
}
1
  • Simple JOIN should suffice Commented Dec 6, 2020 at 13:10

3 Answers 3

2

Using JOIN:

-- could be wrapped with JSON_ARRAYAGG if needed
SELECT JSON_OBJECT('id', r.id,
                   'time', r.time,
                   'user_id', r.user_id,
                   'user', JSON_OBJECT('id', u.id, 'name', u.name)
       ) AS result
FROM reservations r
JOIN users u
  ON r.user_id = u.id

db<>fiddle demo

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, is there a way to get a similar result while avoiding having to type every column name and just use the asterisk (*)? Like SELECT reservations.*, users.* ...
@John Glad I could help. As for SELECT * I am not aware of such functionality for MySQL
OK then, I just made a PHP function that loops all column names of the table that I fetch using "DESCRIBE $tableName" and returns a string to fill JSON_OBJECT() parameters. Helps me avoid typing 50 column names in there :) Thank you!
0

I don't see any advantage to a nested structure. Simply return the columns you want:

select r.*, u.name as user_name
from reservation r join
     user u
     on r.user_id = u.id

2 Comments

What if both tables have an "id" column, there will be overwriting unless I specify different names using "as" keyword. And if there are too many columns this will become a burden. That's why I want to keep the default names for columns and keep user columns separate in another array, preferably using (*) symbol while selecting.
@John . . . The id column is the same due to the JOIN condition. It is redundant to return it twice.
-1

You can get the data you want with a join.

SELECT reservations.id, reservations.time, reservations.user_id, users.name FROM reservations LEFT JOIN users ON users.id = reservations.user_id

1 Comment

This is basic joining. this will give data on the same level, not as a nested array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.