我需要从这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_user
且user_2
等于users
。id
现在如果只有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
记录
答案 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
;