一起加入3张桌子

时间:2012-01-10 18:32:04

标签: mysql sql

我需要从这3个表中检索数据

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 |
+----+--------+--------+

我需要选择所有这些数据,但仅限user_1等于random number的地方 并且user_2等于from_useruser_2等于usersid现在如果只有2个表我选择我需要的数据没问题但我不知道如何加入表3,users我的当前查询没有包含users表:

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

编辑感谢您的答案,它完美无缺,

但是,如果我只需要从messages获取最后一条记录,那该怎么办呢?因为现在它获得all_messages.user_2 = messages.from_user的所有记录,而我只需要获得最后一个newest记录

3 个答案:

答案 0 :(得分:3)

您只需使用第三个表格为您的查询添加另一个“加入”:

SELECT `all_messages`.`user_1`, `messages`.*
FROM `all_messages`
JOIN `messages` 
ON (`all_messages`.`user_2` = `messages`.`from_user`) 
JOIN  `users`
ON (`users`.`id` = `all_messages`.`user_2`)
WHERE `all_messages`.`user_1` = '12'
ORDER BY `messages`.`id` DESC LIMIT 2

答案 1 :(得分:1)

您只需添加一个新的联接,如下所示:

SELECT `all_messages`.`user_1`, `messages`.*
FROM `all_messages`
JOIN `messages` ON (`all_messages`.`user_2` = `messages`.`from_user`) 
JOIN users      ON (...write your condition here...)
WHERE `all_messages`.`user_1` = '12'
ORDER BY `messages`.`id` DESC LIMIT 2

答案 2 :(得分:1)

SELECT
    users.username,users.last_name,messages.* 
FROM
    (SELECT * FROM all_messages WHERE user_1=12) all_msgs
    INNER JOIN users ON messages.id = users.id
    INNER JOIN messages ON all_msgs.user_2 = messages.from_user
ORDER BY
    messages.id DESC LIMIT 2
;