简体   繁体   中英

Athena SQL create table from variable number of tables

I want to create a table / view from variable multiple table names that I get from a SELECT query.
It's possible to create a table from multiple known tables like so:

CREATE TABLE new_table AS
SELECT column_1, column_2
FROM clients_1, clients_2, ... clients_n;

To get list of tables I can use something like:

SELECT DISTINCT table_name FROM information_schema.columns WHERE table_name like '%clients_%';

Which returns:

     table_name
1    clients_1
2    clients_2

How can I use the table names result as a list in CREATE TABLE FROM clause?

I tried something like this with a WITH:

WITH mytable AS 
  (SELECT DISTINCT table_name FROM information_schema.columns WHERE table_name like '%clients_%')
    CREATE TABLE new_table AS
    SELECT column_1, column_2
    FROM mytable;

But it's mostly not working.
And even if it does, for example by not using WITH and selecting * columns -

CREATE TABLE new_table AS
SELECT *
FROM (SELECT DISTINCT table_name FROM information_schema.columns WHERE
table_name like '%clients_%');

new_table is just a copy of mytable/nested query.

Ideas?
Thanks!

I ended up going with a VIEW like so:

CREATE OR REPLACE VIEW clients_all AS
  SELECT column_1, column_2 FROM client1
  UNION ALL
  SELECT column_1, column_2 FROM client2

The downside is I'll have to update the view whenever adding new client_n table, And explicitly specify the name of the tables rather than inferring them from a query,
But I probably had to break it into two queries anyway even if creating a table as originally intended.

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