0

我有以下 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文件夹所有者的用户名(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'

4

2 回答 2

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

因此,根据需要多次加入表,但给每个人一个不同的别名。

于 2012-10-09T15:20:03.083 回答
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

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

于 2012-10-09T15:22:21.087 回答