In my system (PHP/MySql) I have a User table and Images table. One User can have many Images.
I have a page where a need to list all Users(even if the user don't have Images) and all Images, for each user. How can I get this?
Solution 1
$users = query('SELECT * FROM Users')
then
foreach($users as $user) $user->images = query('SELECT id, path, size FROM Images WHERE user_id = ' . $user->id)
Solution 2
$users = query('SELECT *, (SELECT GROUP_CONCAT(id,path,size) FROM Images) as images FROM Users')
then
foreach($users as $user) list($id,$path, $size) = explode(',', $user->images) $user['images'] = ['id' => $id, 'path' => $path, 'size' => $size];
There is a better way to acomplish this?
P.S. 1: Using LEFT JOIN duplicate the results.
P.S. 2: Using INNER JOIN / JOIN , Users that don't have Images are ignored.