具有相同表的多个连接的SQL

时间:2013-03-01 16:29:00

标签: php mysql sql

我正在建立一个论坛,我遇到了一个带有很多连接的SQL select的问题。我想在同一行显示两个不同用户的图像。

用户的第一张图片是谁写了主题,第二张图片是最后回复的用户。

我构建的查询:

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。

4 个答案:

答案 0 :(得分: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

请注意我如何使用其他名称usersu1调用u2表的每个实例。另请注意我是如何指定列别名来区分同名的两列(例如creatorPhotoreplierPhoto)。这样,您就可以将名称用作PHP关联数组 a la $post['creatorPhoto']的索引。

是的,我默默地将您的内联变量更改为参数。把它作为一个提示。 :-D

答案 1 :(得分:1)

除了from子句中缺少别名之外,您还可能遇到whereorder by子句的问题。您需要为那些列使用别名。

我不知道他们来自哪里,但有点像:

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

假设所有人都来自posts

答案 2 :(得分: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

答案 3 :(得分: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