I am using PHP and MYSQL to display an overview for the latest user activities.

I have like five activities, but lets say we just have two activities (posts and comments), so basically using MYSQL I have to get results from two tables ordered by a date column (all the activities tables have a date column), then using PHP I need to loop through those results and for each result type (either a post or a comment) I need to handle it differently (posts and comments have different html).
The first thing that was on my mind is the MYSQL UNION ALL Operator but w3schools says
each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order
And my posts and comments tables don't have the same number of columns or data types, also I don't know how to handle each result type differently.
I am lost right know, if you could help me in any way that would be great, Thank you.
Here is an example of posts and comments tables
-- Comments table
id|user_id|post_id|c_date|comment
-- Posts table
id|user_id|p_date|title|content
I am not trying to join rows, I want to display each row as it's own, not joined it with another row.
SELECT column 1, column 2, '' AS 'column 3' FROM table a
UNION
SELECT column 1, column 2, column 3 FROM table b
You can use UNION in the following way if you know the structure of the tables before hand
There is no "elegant" way to do this in one single query. I recommend the following:
type (comment/post/...) field to each result rowWith the type on each result row, you can decide how to render it in your loop (use different html).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With