2

我有 3 张桌子:

  • tblPosts
  • tbl评论
  • tbl用户

我正在尝试获取帖子列表以及相关评论。棘手的部分似乎是让帖子和评论显示正确的作者(用户)。这是我得到的最接近的,但是帖子作者不正确。我将我的 CFOutput 分组在“pid”上,所以我只按照我的预期得到每个帖子一次。

SELECT tblPosts.pid
       , tblPosts.title
       , tblPosts.description
       , tblPosts.price
       , tblPosts.datecreated AS pdate
       , tblPosts.image1
       , tblComments.comment
       , tblComments.datecreated AS cdate
       , tblUsers.fname
       , tblUsers.lname
FROM   tblPosts
          LEFT JOIN tblComments ON tblPosts.pid = tblComments.pid
          LEFT JOIN tblUsers ON tblComments.uid = tblUsers.uid

有什么想法吗?谢谢!

4

2 回答 2

4

由于两个表都包含一个作者 ID,因此您必须加入 tblUser 两次:一次用于帖子,一次用于评论。这意味着您必须使用表别名来区分两者。沿着这些pa思路,“Post Author”ca的别名和“Comment Author”的别名在哪里。

SELECT p.pid
       , p.title  
       , ... 
       , pa.fname AS PostAuthorFirstName
       , pa.lname AS PostAuthorLastName
       , ca.fname AS CommentAuthorFirstName
       , ca.lname AS CommentAuthorLastName
FROM tblPosts p 
        LEFT JOIN tblUsers pa ON pa.uid = p.uid
        LEFT JOIN tblComments c ON p.pid = c.pid
        LEFT JOIN tblUsers ca ON ca.uid = c.uid
于 2013-08-20T04:13:48.107 回答
1

我不熟悉您表中的所有字段。将帖子也加入到用户表中,以获取特定用户来撰写帖子。

试试这个怎么样:

SELECT p.pid
       ,p.title
       ,p.description
       ,p.price
       ,p.datecreated AS pdate
       ,p.image1
       ,c.comment
       ,c.datecreated AS cdate
       ,u1.fname AS CommentAuthorsName
       ,u1.lname AS CommentAuthorsLastName
       ,u2.fname AS PostAuthorName
       ,u2.lname AS PostAuthorLastName
FROM tblPosts p
LEFT JOIN tblComments c
ON p.pid = c.pid
LEFT JOIN tblUsers u1
ON c.uid = u1.uid
LEFT JOIN tblUsers u2
ON p.uid = u2.uid
于 2013-08-20T04:11:17.980 回答