Proper JOIN for Adding a 4th Table to a Query

霸气de小男生 提交于 2019-12-11 11:58:16

问题


Asked a similar question HERE but this extends it.

Here's the original query:

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

I need to add a fourth table (tblPostStatus) that holds the status of each post(statusType) which can be one of 2 different values. When I try to add the JOIN I seem to get duped rows, one for each row in tblPostStatus (there are 3 records in this table). This table has fields sid, pid, uid, statusType.

New Query:

    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

See query result pics:

Do these results look proper or am I doing something incorrectly?


回答1:


(Summary from chat)

The overall requirements changed a bit. Ultimately "Status" is related to a post, user and comment record, so status was moved to the comment table. An additional requirement was added: identify posts with "claim" comments.

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


来源:https://stackoverflow.com/questions/18413615/proper-join-for-adding-a-4th-table-to-a-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!