Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display results from multiple mysql tables orderd by a date column in one loop

Tags:

php

mysql

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

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.

Extra

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

Update1

I am not trying to join rows, I want to display each row as it's own, not joined it with another row.

like image 361
Zakaria Esbaiy Avatar asked Dec 06 '25 14:12

Zakaria Esbaiy


2 Answers

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

like image 118
Kaushal Shah Avatar answered Dec 08 '25 04:12

Kaushal Shah


There is no "elegant" way to do this in one single query. I recommend the following:

  1. write and execute a query for each table
  2. Map results to php array and add a type (comment/post/...) field to each result row
  3. sort the array by date (e.g. with usort)

With the type on each result row, you can decide how to render it in your loop (use different html).

like image 28
dantodev Avatar answered Dec 08 '25 02:12

dantodev