3表SELECT查询的正确语法

时间:2013-08-20 03:51:49

标签: sql coldfusion

我有3张桌子:

  • tblPosts
  • tblComments
  • 向tblUsers

我正在尝试获取帖子列表以及相关评论。棘手的部分似乎是让帖子和评论显示正确的作者(用户)。这是我得到的最接近但是帖子作者不正确。我将我的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

有什么想法? 谢谢!

2 个答案:

答案 0 :(得分:4)

由于两个表都包含作者ID,因此您必须两次加入tblUser:一次用于帖子,一次用于评论。这意味着您必须使用表别名来区分这两者。这些内容包括:pa是“帖子作者”的别名,ca是“评论作者”的别名。

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

答案 1 :(得分:1)

我不熟悉你表格中的所有字段。将帖子加入users表以获取撰写帖子的特定用户。

尝试这个怎么样:

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