Let’s say I have 3 DB tables in MySQL:
t1
t2
t3
And each of them has the same columns I am interested in.
And also each of them has some other columns that I am not interested in.
Now, the common columns in all of them I want to put into the final result are name
, age
, created_at
.
And I want to grab all the data (we are not concerned about the performance – it’s an intranet application, so, 2 or 3 seconds per query is nothing of concern) and sort them by created_at
while creating the result.
So, when accessing the result in PHP and doing a while loop the output will be already sorted chronologically.
How to do that in MySQL?
2
Answers
You’ll want to use a UNION query. This allows you to combine the results of multiple SELECT statements into a single result set, which can then be ordered as you require.
Note that UNION by default removes duplicate rows. If you want to include duplicates, use UNION ALL instead.
Ensure that the columns you’re combining with UNION have compatible data types across all tables.
With UNION you can put several tables in one query, but the result is handled as one.
Here an example
Table 1
Table 2
Table 3