2

我正在建立一个论坛,但我遇到了一个带有许多连接的 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。
4

4 回答 4

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 关联数组的索引la $post['creatorPhoto']

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

于 2013-03-01T16:31:04.823 回答
1

除了子句中缺少别名之外,and子句from也可能存在问题。您需要为那里的列使用别名。whereorder by

我不知道它们来自哪里,但类似:

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

假设所有来自posts.

于 2013-03-01T16:31:23.823 回答
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
于 2013-03-01T16:31:49.500 回答
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
于 2013-03-01T16:33:06.907 回答