正确连接将第4个表添加到查询中

时间:2013-08-24 00:11:17

标签: sql join coldfusion

问了一个类似的问题HERE,但这延伸了它。

这是原始查询:

SELECT  p.pid
    , p.title
    , p.description
    , p.price
    , p.datecreated AS pdate
    , p.image1
    , c.cid
    , c.comment
    , c.datecreated AS cdate
    , pa.fname AS PFName
    , pa.lname AS PLName
    , ca.fname AS CFName
    , ca.lname AS CLName
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
ORDER BY p.pid

我需要添加第四个表(tblPostStatus)来保存每个帖子的状态(statusType),它可以是两个不同的值之一。当我尝试添加JOIN时,我似乎得到了duped行,tblPostStatus中每行一个(此表中有3条记录)。该表包含字段sid,pid,uid,statusType。

新查询:

    SELECT  p.pid
    , p.title
    , p.description
    , p.price
    , p.datecreated AS pdate
    , p.image1
    , c.cid
    , c.comment
    , c.datecreated AS cdate
    , pa.fname AS PFName
    , pa.lname AS PLName
    , ca.fname AS CFName
    , ca.lname AS CLName
    , ps.statusType
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
LEFT JOIN tblPostStatus ps ON p.pid = ps.pid
ORDER BY p.pid

查看查询结果图片: Original

New

这些结果看起来是否合适,或者我做错了什么?

1 个答案:

答案 0 :(得分:2)

(聊天摘要)

整体要求有所改变。最终,“状态”与帖子,用户评论记录相关,因此状态已移至评论表。增加了一项额外要求:确定具有“索赔”评论的帖子。

SQL Fiddle

SELECT  p.pid
    , p.title
    , c.cid
    , c.comment
    , c.statusType 
    , COALESCE(cnt.HasClaim, 0) AS HasClaim
    , pa.fname AS PFName
    , pa.lname AS PLName
    , ca.fname AS CFName
    , ca.lname AS CLName
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
      LEFT JOIN (
          SELECT pid, COUNT(*) AS HasClaim
          FROM  tblComments 
          WHERE statusType = 1
          GROUP BY pid
        ) cnt ON cnt.pid = p.pid
ORDER BY p.pid, c.cid