简体   繁体   中英

Selecting not joined data from several tables in MySQL

I have several MySQL tables with the same structure. They all have a date field. 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.

PS: 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

为什么不使用可以合并表的VIEW,然后对视图进行排序呢?

You can use a SELECT ... UNION .. SELECT structure

More info: http://dev.mysql.com/doc/refman/5.0/en/union.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM