I need to retrieve data from these 3 tables
users
+----------+-----------+
| username | last_name |
+----------+-----------+
| name | last name |
+----------+-----------+
messages
+----+---------+-----------+---------+------+---------------------+
| id | to_user | from_user | message | read | sent |
+----+---------+-----------+---------+------+---------------------+
| 12 | 12 | 10 | 1 | 0 | 2012-01-10 17:06:14 |
+----+---------+-----------+---------+------+---------------------+
all_messages
+----+--------+--------+
| id | user_1 | user_2 |
+----+--------+--------+
| 1 | 10 | 12 |
+----+--------+--------+
I need to select all this data but only where user_1 is equal to random number
and user_2 is equal to from_user and user_2 is equal to users.id now if there would only be 2 tables i have no problem selecting data i need but i don’t know how to join table 3 which is users there is mine current query without users table included:
SELECT `all_messages`.`user_1`, `messages`.*
FROM `all_messages`
JOIN `messages`
ON (`all_messages`.`user_2` = `messages`.`from_user`)
WHERE `all_messages`.`user_1` = '12'
ORDER BY `messages`.`id` DESC LIMIT 2
EDIT Thank you for your answers it worked perfectly,
But what if i need to get only last record from messages because now it gets all records where all_messages.user_2 = messages.from_user and i need to get only one last newest record
you just add another “join” to your query with the third table: