我有一个MySQL数据库(名为“sitefeather”),最终会有几个具有相同结构的表。结构如下:
id INT(11) NOT NULL auto_increment, site VARCHAR(1000) NOT NULL, action1 BIGINT(9) NOT NULL, action2 BIGINT(9) NOT NULL, createddatetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id), UNIQUE (site)
我想打印所有表中最近添加的25个条目(在每个表中称为“站点”)的列表。我怎么能用PHP做到这一点?
提前致谢,
约翰
编辑:我如何为可变的多个表做这个?
答案 0 :(得分:3)
你想要做的事情是:
(
select 't' as table_name, id, createdatetime
from t
order by createdatetime desc
limit 25
)
union
(
select 'u' as table_name, id, createdatetime
from u
order by createdatetime desc
limit 25
)
union
(
select 'v' as table_name, id, createdatetime
from v
order by createdatetime desc
limit 25
)
order by createdatetime desc
limit 25
这应该保证您在各个表的createdatetime
字段中拥有的任何索引的好处,并且允许您确定从哪个表中选择了25个结果ID。
答案 1 :(得分:2)
来自http://dev.mysql.com/doc/refman/5.0/en/union.html
(SELECT id FROM table1)
UNION ALL
(SELECT id FROM table2)
UNION ALL
(SELECT id FROM table3)
UNION ALL
(SELECT id FROM tableN)
ORDER BY createdatetime DESC
LIMIT 25
答案 2 :(得分:1)
如果您要这样做,或者出于其他原因一次查询所有表格,您可能需要set up a MERGE table以便更轻松地访问组合数据。
CREATE TABLE merged_table (
id INT(11) NOT NULL auto_increment,
site VARCHAR(1000) NOT NULL,
action1 BIGINT(9) NOT NULL,
action2 BIGINT(9) NOT NULL,
createddatetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(id),
UNIQUE (site)) ENGINE=MERGE UNION=(table1,table2,table3,tableN) INSERT_METHOD=LAST;
但是,只有在每次查询相同的表时,此方法才有效。