2012-01-10 62 views
1

我需要從這3個表中檢索數據加入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 numberuser_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記錄

+0

你有主列在用戶? – SergeS 2012-01-10 18:37:09

回答

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

你只需要添加一個新的連接,就像這樣:

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