简体   繁体   English

从多个表中选择的最佳方法

[英]Best approach to select from multiple tables

I have many tables like A1, B1, C1..etc. 我有很多表格,例如A1,B1,C1..etc。 all with the same row structure 所有具有相同的行结构

Moz -  Attr1 - attr2

And one table that contains the names of all tables like: 一个表包含所有表的名称,例如:

Id(pk) - tname - input
1          A1      X
2          B1      Y
3          C1      Z

I'm looking for the best approach to get all of the A1, B1, C1 values in one view. 我正在寻找在一个视图中获取所有A1,B1,C1值的最佳方法。 If possible without using UNION 如果可能,不使用UNION

If all your tables have the same structure, then all the data really belongs to one table. 如果所有表都具有相同的结构,则所有数据实际上都属于一个表。 Let's call it XY for the sake of giving it a name here. 为了在此处命名,我们将其称为XY

The table name "A1, B1" ... etc should be just another field in the XY table: 表名称“ A1,B1” ...等应仅是XY表中的另一个字段:

Moz -  Attr1 - attr2 - context
-      -       -       A1
-      -       -       B1

This table indeed needs to be properly indexed. 该表确实需要正确索引。
Assuming the Moz field is a primary key for each table, you then need to have (Moz,Context) as primary key in order to avoid issues with duplicate Moz values. 假设Moz字段是每个表的主键,那么您需要将(Moz,Context)作为主键,以避免出现重复的Moz值问题。

Getting an union of all tables is then just as simple and fast as a SELECT * from XY . 这样,获取所有表的并集就如同SELECT * from XY执行SELECT * from XY一样简单快捷。

If you need to select a few of the tables: SELECT * from XY WHERE context IN ('A1', 'B1') 如果您需要选择一些表: SELECT * from XY WHERE context IN ('A1', 'B1')

Generally speaking, it is a very bad idea to use dynamically created tables in a SQL RDBMS, because it completely defeats the purpose of "Relational", and will cause performance to be abysimal. 一般而言,在SQL RDBMS中使用动态创建的表是一个非常糟糕的主意,因为它完全违背了“关系”的目的,并且会导致性能下降。

You just actually found out the hard way, because technically, your A1, B1, C1 tables are unrelated, and yet you want them to become related via the use of a union, which you don't want to use because it is "slow". 您实际上只是发现了一条艰难的路,因为从技术上讲,您的A1,B1,C1表是不相关的,但是您希望它们通过使用并集而成为关联,而您不想使用它,因为它“很慢”。
By storing the name as a field, you create a relation between the "table list" table and XY, can now use reasonably fast joins, and no further "CREATE TABLE" are ever needed. 通过将名称存储为字段,可以在“表列表”表和XY之间创建关系,现在可以使用合理的快速连接,并且不再需要“创建表”。

See Database normalization to have a better explanation of these concepts. 请参阅数据库规范化以更好地解释这些概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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