2013-03-01 99 views
2

我正在建立一個論壇,並且我有一個與許多連接的SQL選擇的問題。我想在同一行中顯示兩個不同用戶的圖像。SQL與多個連接相同的表

用戶的第一張圖片是誰寫的話題,第二張圖片是上次回覆的用戶的圖片。

我建立查詢:

SELECT 
posts.*, users.photo, users.displayname FROM posts 
JOIN users ON(posts.useraid = users.id) 
JOIN users ON(posts.lastreply = user.id) 
WHERE forumid='$forumid' and type='post' ORDER BY `timee` DESC 
  • posts.lastreply =最後回覆用戶的ID。
+2

又有什麼問題呢? – GarethL 2013-03-01 16:30:16

+3

你需要爲每個連接使用不同的別名... – 2013-03-01 16:30:57

回答

3

您必須指定一個別名使用AS關鍵詞的每個表:

SELECT posts.*, 
    u1.photo AS creatorPhoto, u1.displayname AS creatorName, 
    u2.photo AS replierPhoto, u2.displayname AS replierName 
FROM posts 
JOIN users AS u1 ON(posts.useraid = u1.id) 
JOIN users AS u2 ON(posts.lastreply = u2.id) 
WHERE forumid= @forumid and type='post' 
ORDER BY `timee` DESC 

注意我是如何用不同的名字叫users表的每個實例 - u1u2。另請注意,我如何指定列別名來區分同名的兩列(例如creatorPhotoreplierPhoto)。這樣,您可以使用該名稱作爲PHP關聯數組的索引a la$post['creatorPhoto']

是的,我默默地將你的內聯變量改爲一個參數。把它當作暗示吧。 :-D

+0

好的,那麼我如何獲得第二個圖像和顯示名稱? – GuyChabra 2013-03-01 16:33:36

+0

@ user2124281我已經將它們添加到查詢中的SELECT子句中。例如,請注意'u1.photo'和'u2.photo'。 – 2013-03-01 16:36:25

+0

偉大的作品,唯一的問題是,如果「lastreply」=「」帖子不顯示。 – GuyChabra 2013-03-01 16:40:29

1

除了缺乏from子句中的別名,你也可以擁有與whereorder by第一個問題。您需要爲那裏的列使用別名。

我不知道哪裏來的,但這樣的:

WHERE posts.forumid='$forumid' and posts.type='post' 
ORDER BY posts.`timee` DESC 

假設全部來自posts

1

你需要爲這個別名工作

SELECT 
posts.*, u1.photo, u1.displayname, u2.photo, u2.displayname FROM posts 
JOIN users u1 ON posts.useraid = u1.id 
JOIN users u2 ON posts.lastreply = u2.id 
WHERE forumid='$forumid' and type='post' ORDER BY `timee` DESC 
1
SELECT posts.*, author.photo as author_photo, author.displayname as author+name, 
     replier.photo as replier_photo, replier.displayname as replier_name 
FROM posts 
    JOIN users author ON(posts.useraid = users.id) 
    JOIN users replier ON(posts.lastreply = user.id) 
WHERE forumid='$forumid' and type='post' ORDER BY `timee` DESC 
+0

if lastreply =「」該帖子未顯示...任何解決方案? – GuyChabra 2013-03-01 16:45:34

+0

將JOIN更改爲LEFT OUTER JOIN。 (改變兩者。) – 2013-03-01 16:46:49

+0

作品謝謝老兄!我可以有你的Skype?爲未來的問題? – GuyChabra 2013-03-01 16:48:42