Friday, 23 August 2013

Proper JOIN for Adding a 4th Table to a Query

Proper JOIN for Adding a 4th Table to a Query

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?

No comments:

Post a Comment