SQL与多个连接相同的表
问题描述:
我正在建立一个论坛,并且我有一个与许多连接的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。
答
您必须指定一个别名使用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
表的每个实例 - u1
和u2
。另请注意,我如何指定列别名来区分同名的两列(例如creatorPhoto
和replierPhoto
)。这样,您可以使用该名称作为PHP关联数组的索引a la$post['creatorPhoto']
。
是的,我默默地将你的内联变量改为一个参数。把它当作暗示吧。 :-D
答
除了缺乏from
子句中的别名,你也可以拥有与where
和order by
第一个问题。您需要为那里的列使用别名。
我不知道哪里来的,但这样的:
WHERE posts.forumid='$forumid' and posts.type='post'
ORDER BY posts.`timee` DESC
假设全部来自posts
。
答
你需要为这个别名工作
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
答
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
又有什么问题呢? – GarethL 2013-03-01 16:30:16
你需要为每个连接使用不同的别名... – 2013-03-01 16:30:57