Selecting not joined data from several tables in MySQL
I have several MySQL tables with the same structure. They all have a date fiel开发者_如何学运维d. I have to build one list in PHP that shows all the rows in these tables, ordered by date. The rows will be mixed in this list, the only criterium for ordering is the date.
For instance:
table1.name; 2011-4-11 05:45h
table6.name; 2011-4-11 10:30h
table3.name; 2011-4-11 15:45h
table2.name; 2011-4-16 09:30h
Is it possible doing these using a MySQL query or have I to make one select per table and mix data with PHP? There aren't joined tables, they are equal tables and I have to show all their data.
P.S.: I can't make one unique table and add a type field, I have being asked to keep the tables as they are.
Well, arguably you can sort of.
Select 'table1' as name, mydate from table1
union (select 'table2' as name, mydate from table2) as tmp ...
order by mydate
union works assuming the same structure, eg in this case name, date, and appends them into one list and then you can sort them
Why not use a VIEW that can be a union of the tables, and then you can do sorting on the view?
You can use a SELECT ... UNION .. SELECT
structure
More info: http://dev.mysql.com/doc/refman/5.0/en/union.html
精彩评论