sql在一个查询中获取两次用户名

时间:2012-10-09 15:05:55

标签: sql

我有以下3个表格:

users:
id, username

folders:
id,fkuser(connects to user.id)

folder_comments:
id,fkuser(connects to user.id), fkfolder(connects to folder.id)

我想获取评论者用户名(folder_comments.fkuser->user.id<->user.username AND 以及文件夹所有者的用户名(folder_comments.fkfolder->folder.id<->folder.fkuser->user.id<->user.username);

我遇到的问题是部分:

SELECT `folder_comments`.*, `folder`.`fkuser` as folderuserid, `user`.`firstname` as username
FROM `folder_comments` 
                left join `folder` on `folder_comments`.`fkfolder` = `folder`.`id`
                left join `user` on `folder_comments`.`userid` = `user`.`id`

如何获取文件夹的所有者用户名?

编辑:

我试过了:

    SELECT `folder_comments`.*, `folder`.`fkuser` as folderuserid, `user`.`firstname` as username, , `user`.`firstname` as folderowner
        FROM `folder_comments` 
                        left join `folder` on `folder_comments`.`fkfolder` = `folder`.`id`
                        left join `user` on `folder_comments`.`userid` = `user`.`id`
left join `user` on `folder`.`fkuser` = `user`.`id`

但我收到错误Not unique table/alias: 'user'

2 个答案:

答案 0 :(得分:1)

不确定我的模式中的位置

但你这样做。这是从人们那里得到妈妈和爸爸的名字

Select Child.Name,Mothers.Name, Father's.Name
From Child
Inner Join People Mothers On Child.MotherID = Mothers.PersonID
Inner Join People Fathers On Child.FatherID = Fathers.PersonID

因此,根据需要多次加入桌面,但为每个人提供不同的别名。

答案 1 :(得分:1)

多次使用用户加入,如下所示:

select folder.*, userfolder.username, comment.*, usercomment.username
  from folders folder inner join
  user userfolder on folder.fkuser = userfolder.id inner join
  comments comment on comment.fkfolder = folder.id inner join
  user usercomment on comment.fkuser = usercomment.id

在连接中多次使用同一个表时,使用不同的别名

非常重要