1

在这里问了一个类似的问题,但这扩展了它。

这是原始查询:

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 时,我似乎得到了欺骗行,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

查看查询结果图片: 原来的

新的

这些结果看起来正确还是我做错了什么?

4

1 回答 1

2

(聊天总结)

总体要求发生了一些变化。最终,“状态”与帖子、用户评论记录相关,因此状态被移至评论表。增加了一个额外的要求:识别带有“声明”评论的帖子。

SQL小提琴

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
于 2013-08-25T17:45:08.587 回答