Query with sub queries for forum flags work, but not entirely... can't figure out why
I'm hoping you can help! My forum has now got flags in place to indicate (a) which threads a user has posted in, and (b) which thread is new, or has new content based on the date the user last looked at the thread.
The first bit (a) works fine where a user is the original poster or a respondent then a tick appears next to the thread in the results list.
The second bit (b) works to a point, but not entirely as expected. So, to explain... I have a table called tbl_forumREADS that is collecting the info from a users viewings of a thread. If it's the first view, a record is created storing the User ID, the Thread ID and the date it was viewed, if it's a subsequent viewing of the thread, then the date of the record equal to the thread ID and the User ID is updated. This all works fine within the database. The user then has a visual flag before viewing a thread to let him know that it's new or has been updated which displays based on a show if the viewed date is less than the thread date. Sounds simple!
My issue is that if the user views a thread, it's recorded and the flag disappears, but if another user then enters a reply, the visual flag should reappear indicating that the thread has been updated, but the updated flag isn't showing.
Here's my select:
SELECT
EXISTS (SELECT * FROM tbl_forumPOSTS b WHERE fld_fTHREADID = tbl_forumPOSTS.fld_fID AND fld_fUSERID = ".$Uid.") UserRepliedToThread,
IF(tbl_forumPOSTS.fld_fUSERID = ".$Uid.", 1, 0) UserStartedThread,
(
SELECT fld_fREPLYDATE FROM tbl_forumPOSTS sP WHERE sP.fld_fTHREADID = tbl_forumPOSTS.fld_fID AND sP.fld_fUSERID = ".$Uid."
ORDER BY fld_fREPLYDATE DESC
LIMIT 1
) LastReadByUser,
(
SELECT fld_readsDATE FROM tbl_forumREADS fR WHERE fR.fld_readsTHREADID = tbl_forumPOSTS.fld_fID AND fR.fld_readsUSERID = ".$Uid."
ORDER BY fld_readsDATE DESC
LIMIT 1
) LastReadPost,
tbl_forumPOSTS.*,
`tbl_forumNAME`.`fld_fnNAME` AS tbl_forumNAME_fld_fnNAME, tbl_users.*
FROM tbl_forumPOSTS
JOIN tbl_forumNAME ON tbl_forumNAME.fld_fnID = tbl_forumPOSTS.fld_fFORUMID
JOIN tbl_users ON tbl_forumPOSTS.fld_fUSERID = tbl_users.UserID
WHERE fld_fTHREADID = 0
AND fld_fSHOW = 1
AND tbl_forumPOSTS.fld_fFORUMID = %s
ORDER BY fld_fREPLYDATE DESC
And here's my show if:
if (!$row_WADAtbl_forumPOSTS['LastReadPost'] > $row_WADAtbl_forumPOSTS['LastReadByUser']) {
What's wrong?
As a side note, the show if acts strange anyway. If I remove the NOT (!) and switch to LastReadByUser is less than LastReadPost, then flags only appear on those threads that have been read. I would have thought that this was exactly the same as the NOT statement I have in place.
Just want some extra eyes on this that might see something wrong!