I have a fairly complicated notification system that I am working on, it’s quite simple for the most part, the complexity gets into checking other tables whether or not the content has been removed or not, and I have multiple tables of data that all goes into the notification system, so it has to check each of those, and I have to be able to easily be able to add more tables as I build the website to allow other notification types to be added, and with the current query i am using it does not allow that, I have tried to come up with a better way of doing this, however I am not good enough with mysql queries to do so, so I am hoping I could get some (or it may turn out to be alot) of assistance by one (or some) of you.
Here’s my current query:
SELECT
n.*,
MIN(n.state) state,
MIN(n.status) status,
MAX(n.date) maxDate
FROM notifications n
LEFT JOIN comments c
ON n.type = 'comment'
AND n.uniqueID = c.id
AND c.state='0'
LEFT JOIN posts p
ON n.type = 'post'
AND p.id = n.uniqueID OR n.type = 'comment'
AND p.id = c.postID
WHERE n.toID = '$session'
AND p.state = 0
GROUP BY n.uniqueID
ORDER BY status ASC, maxDate DESC
So what the above statement does, in a nutshell, is this. It selects notifications from the notification table, in this table there is a column for type and uniqueID of that content. So for each row that’s type is posts it checks the post table where the uniqueID from notifications is the same as the unique id in the posts table, which it then checks the state of that post to see if it has been deleted or not (if it has not been removed, state=0, else I don’t want it). The same goes for comments.
So I need a way to do everything just like this does it, however I need it to be easier to continuously add new table checks to it. I have been trying to add another left join for a table called likes, however i am unable to get it to work together, for whatever reason. However I have come up with this code that will do what I want it to. (only for the likes table though, it does not include any other table which i need it to)
SELECT
n.*,
MIN(n.state) state,
MIN(n.status) status,
MAX(n.date) maxDate
FROM notifications n
LEFT JOIN likes l
ON n.type = 'likes'
AND n.uniqueID = l.id
WHERE n.toID = '$session'
AND l.state='0'
GROUP BY n.uniqueID
ORDER BY status ASC, maxDate DESC
I hope someone can help me out with this solution, thank you so much in advance!
In looks like you could use an “ANY” subquery
http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html