MySQL – How to Select All Results from Two Independent Tables

MySQLselect

I have two tables:

Comments
--------
id
comment_content
time_stamp

Activities
-----------
id
activity_content
time_stamp

And I would like to combine the results from both, ordered by their timestamp fields.

Best Answer

Combine the two tables with UNION and ORDER BY timestamp. You can also add an addition (type) column so the source of a row can be identified:

SELECT 
    'comment' AS type, id, comment_content AS content, time_stamp
FROM
    comments

UNION ALL

SELECT 
    'activity', id, activity_content, time_stamp
FROM
    activities

ORDER BY 
    timestamp ;