简体   繁体   中英

How to JOIN a group of tables in a database with similar name using SQL query?

For example, I have a Database called db, and there are 100 tables in it called ta_1 ... ta_100 respectively. Each table has two columns id(int) and val(int) .

  1. If I want to get the overall mean of val, what should I do?
  2. If I want to get a table as a result with two column: tablename(String) and mean(float), what should I do?

It goes without saying that you should not have set up your database this way. There are a number of solutions, ranging from easy but mundane, to hard but useful.

At some point, you have to create a list of tables, and prepare a statement that merges them together. Copy&Past using a database view would be a good start:

create view GlobalView (
    tabname varchar(10),
    id int,
    val int)
as
   select 'ta_1', id, val from ta_1
UNION ALL
   select 'ta_2', id, val from ta_2
UNION ALL
   select 'ta_3', id, val from ta_3
UNION ALL
   .....
UNION ALL
   select 'ta_100', id, val from ta_100

Then, you can simply run the select:

select avg(1.0 * val) as mean
from GlobalView

The alternative would be to create a dynamic query that you can call either from an external program, or by using 'dynamic SQL'

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