Show multiple joined rows
Question
I have a simple relational MySQL database with users, cars an a log table. Everything works fine. In the log table I want to 'register' the users of a car. But a car can have two users at the same time.
My question: How can I show multiple users in the log table, using the relational database?
My database structure:
Table users
user_id name phone
------- ----- -----
1 john 123
2 kevin 456
Table cars
car_id nr brand
------ --- -----
1 666 Ford
2 999 Dodge
Table log
log_id car_id user_id1 user_id2
------ ------ -------- --------
1 1 1 2
The car.car_id
is related to log.car_id
and users.user_id
is related to log.user_id1
and log.user_id2
.
Supposed SQL:
SELECT log.*, cars.*, users.*
FROM log
LEFT JOIN cars ON log.car_id=car.car_id
LEFT JOIN users ON log.user_id1=users.user_id
LEFT JOIN users ON log.user_id2=users.user_id
PHP (in loop of course):
echo $row["brand"];
echo $row["name"]; // user_id1
echo $row["name"]; // user_id2
It's working for only one name. How to show the names of user_id1
and user_id2
in the same "log" row?
Solution
Try using aliases like this:
SELECT l.*, c.*, u1.*, u2.*
FROM log l
LEFT JOIN cars c ON l.car_id=c.car_id
LEFT JOIN users u1 ON l.user_id1=u1.user_id
LEFT JOIN users u2 ON l.user_id2=u2.user_id
(Note that it's bad practice to use "SELECT *" except for ad-hoc queries. So you should instead enumerate the exact columns you want to select.)