[英]postgresql querying on multiple identical tables
Hello I have several databases, such as mytable_2009_11_19_03
where last 2 numbers identify the hour (table for 03:00), now I want to query something from _00 to _23 . 您好我有几个数据库,例如mytable_2009_11_19_03
,其中最后2个数字标识小时(表格为03:00),现在我想查询从_00到_23的内容。 It could be done in such way but it is really clumsy 它可以这样做,但它真的很笨拙
select * from mytable_2009_11_19_00 where type = 15
UNION
select * from mytable_2009_11_19_01 where type = 15
UNION
...........
select * from mytable_2009_11_19_23 where type = 15
How could I do it easier? 我怎么能这样做更容易? regards 问候
This table structure sounds like it was intended to be part of a data partitioning scheme . 该表结构听起来像是数据分区方案的一部分 。 This is not bad design. 这不错设计。 This is a very good thing! 这是一件非常好的事情!
Time based data like this is always being added to in the front and dropped off the back as it expires. 像这样的基于时间的数据总是被添加到前面并且在它到期时从后面掉落。 Using one huge table would result in large amounts of index fragmentation as the data updates and in very large maintenance times for operations like VACUUM. 使用一个巨大的表会导致数据更新时出现大量索引碎片,并导致VACUUM等操作的维护时间非常长。
If you follow the link I included in the first paragraph and read all about partitioning, you'll be able to use CHECK constraints to make date searches very fast. 如果您按照我在第一段中包含的链接并阅读有关分区的所有内容,您将能够使用CHECK约束来快速进行日期搜索。 Any SELECT that includes a WHERE timestamp > x AND timestamp < y will be quick. 任何包含WHERE时间戳> x AND时间戳<y的SELECT都会很快。
Now, if these tables don't include any timestamps then the partitioning with CHECK constraints won't work and you will just have to write scripts to write the clumsy UNION queries for you. 现在,如果这些表不包含任何时间戳,那么使用CHECK约束的分区将不起作用,您只需编写脚本来为您编写笨拙的UNION查询。
If you know that all the tables generated are always identical in schema, in PostgreSQL you could create a parent table and set the newly created tables to INHERIT from the parent. 如果您知道生成的所有表在模式中始终相同,则在PostgreSQL中您可以创建父表并将新创建的表从父设置为INHERIT。
CREATE TABLE mytable_2009_11_19 (LIKE mytable_2009_11_19_00);
ALTER TABLE mytable_2009_11_19_00 INHERIT mytable_2009_11_19;
ALTER TABLE mytable_2009_11_19_01 INHERIT mytable_2009_11_19;
.
.
.
ALTER TABLE mytable_2009_11_19_23 INHERIT mytable_2009_11_19;
SELECT * FROM mytable_2009_11_19 where type = 15;
This is similar to using a view, but there are differences (listing the CONs first): 这与使用视图类似 ,但存在差异(首先列出CON):
The easiest solution would likely be to build a view of all of the tables, then you can query them easily. 最简单的解决方案可能是构建所有表的视图,然后您可以轻松地查询它们。 You could easily write a procedure to generate the view. 您可以轻松编写一个过程来生成视图。 Also, if you use "union all", it will be faster, if the result you want is all of the rows (as opposed to distinct rows) and you can still grab distinct rows by selecting distinct from the view if you need it sometimes. 此外,如果你使用“union all”,它会更快,如果你想要的结果是所有行(而不是不同的行),你仍然可以通过选择视图中的不同来获取不同的行,如果你有时需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.