如何在MySQL中合并多个具有相似名称的表

sea*_*awk 2 mysql sql merge

可能重复:
如何合并两个MySql表?

我想合并多个具有相同结构的表并创建一个大表.这些表有类似的名称,所以我想使用LIKE语句.谁能告诉我怎么做到这一点?

这些表非常简单,每个表都有一个ID列和一些其他列,但是有大量的表,所有这些表都有名称'TX-xxx',如'TX'德克萨斯州,以及德克萨斯州'xxx'的县; 你知道德克萨斯州有200多个县.(事实上​​,我必须为所有州执行此操作.)所以我想使用该语句"LIKE 'TX-___'".

谢谢!

Kyr*_*yra 5

你必须提供更多信息,以便我们确切地知道你想要什么,但你可以创建一个视图

CREATE VIEW myViewName AS 

select * 
from table1 

union all 

select * from 
table2 
Run Code Online (Sandbox Code Playgroud)

通过这种方式,它将显示来自所有表的信息(并且可以限制,以便在选择中不显示所有内容),并且当table1,table2等被更改时,视图将反映这一点.您可以随时更改它并像从表中一样从中获取:

 select * from myViewName
Run Code Online (Sandbox Code Playgroud)

现在从特定表中获取我不知道如何在mysql中执行此操作,尽管我已经在tsql中完成了.这个上一个问题可以帮助你,所以你可能会有这样的事情:

-- Create temporary table of varchar(200) to store the name of the tables. Depending on how you want to go through the array maybe an id number (int). 
insert into tempTableName (name)
SELECT table_name FROM information_schema.tables WHERE table_schema = 'database_name' and table_name like 'TX_%';
declare @sqlQuery varchar(max)
--Then you will want to loop through the array and build up an sql statement
-- For each loop through:
     if len(@sqlQuery) = 0 begin -- first time through
         set @sqlQuery = 'select col1, col2, col3 from ' + currentTableName
     end else begin -- second+ time through
         set @sqlQuery = 'union all select col1, col2, col3 from ' + currentTableName
     end
-- after the loop add the create view. Could double check it worked by checking length = 0 again
set @sqlQuery = 'CREATE VIEW myViewName AS ' + @sqlQuery
Once the query string is built up you will execute it with
PREPARE stmt FROM @sqlQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Run Code Online (Sandbox Code Playgroud)