Reputation: 532
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
}
}
Upvotes: 0
Views: 365
Reputation: 5053
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
Upvotes: -1
Reputation: 175706
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
Upvotes: 2
Reputation: 1269773
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
Upvotes: 0