dongliang1654 2013-11-13 10:47
浏览 25
已采纳

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

I have many tables like 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. If possible without using UNION

  • 写回答

1条回答 默认 最新

  • doujiang1001 2013-11-13 12:06
    关注

    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.

    The table name "A1, B1" ... etc should be just another field in the XY table:

    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.

    Getting an union of all tables is then just as simple and fast as a SELECT * from XY.

    If you need to select a few of the tables: 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.

    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".
    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.

    See Database normalization to have a better explanation of these concepts.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么