I have two tables called ‘events’ and ‘topics’ each table can have many comments.
What I need to do is list all the events and topics with the amount of comments for each row. I’ve managed to return all the topics, which works great but I don’t know how I can add the events table to the MySql. The comments and events table fields are listed below. Can anyone help me with this query?
Events:
- ID
- Event_Name
Comments:
- post_id <– the releated id for either the events or topics table
-
table <– The table that the row belongs to so either topics or events
SELECT t.id, t.title, c.created_at, IF(ISNULL(c.allComments), 0, c.allComments) AS totalComments FROM topics AS t LEFT OUTER JOIN ( SELECT created_at, post_id, COUNT(*) AS allComments FROM comments GROUP BY post_id ) AS c ON c.post_id = t.id ORDER BY tc.created_at DESC, c.allComments DESC
Sounds like events and topics should be the same table.
Still, I think we can do this with a UNION. Events and Topics have the same columns i hope? (Or at least the same important ones?)
Notice that the ORDER BY applies to the whole UNION, not the individual SELECTs.
The use of LEFT JOIN should allow those rows without Comments to still show. I think the problem is that we have parts of our select dependent on comments (ie – C.table, ordering on last comment, etc). The count should be fine – will just be zero if there are no comments.
You might need to change the SELECT part slightly. I’d like to display C.table so you know whether a row is a topic or event, but im afraid it might screw up the count. Do you need anything from comments besides the count? You use some columns other than post_id and table in your query that you neglected to explain in your question.
You still have columns I don’t know what they are, like Comment’s zoneTable