2013-03-01 104 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