-1

How can I union multiple table in mysql and order by date?

I have 3 differents tables and I want to make a query to get all data inside that and order by date

SELECT * FROM table1, table2, table3 ORDER by date DESC


TABLE 1 

ID  |  USER ID | DATE | 
 2      4        2018

TABLE 2 

ID  |  CAR ID | DATE | 
 3       9      2017

TABLE 3

ID  |  AIR ID | DATE | 
 4      6        2019

I expected result like this

ID | ALLID | DATE
2      4      2018
3      9      2017
4      6      2019
TheCesco88
  • 111
  • 4
  • 9

2 Answers2

0

The correct syntax for union is union/union all. A comma in the from clause is not correct syntax . . . well, for anything.

So:

select id, allid, date from table1
union all
select id, allid, date from table2
union all
select id, allid, date from table3
order by date desc;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You would not be able to create your 2nd column ALLID, however you could use Join to create the tables, but the search results would be difficult if you are trying to search by ID. Can you give more context.

TO Join Table 1 and Table 2 together you need to have a primary key and a foreign key, so a column from table 1 and a cloumn from table 2 that both appear in table 3.

SO you can use ID from Table 1 and Date from table 2 because both are in table 3 so these are your Join accessories: basic join: all data

     SELECT * FROM table1 t1 JOIN table3 t3 JOIN table2 t2

bit more detail: (using on as a where clause to filder based on specific date)

     SELECT * FROM table1 t1 JOIN table3 t3 JOIN table2 t2 ON t3.DATE=t2.DATE