2

重複の可能性:
2つのMySqlテーブルをマージするにはどうすればよいですか?

同じ構造の複数のテーブルをマージして、1つの大きなテーブルを作成したいと思います。テーブルの名前は似ているので、LIKEステートメントを使用します。誰かが私がこれを行う方法を教えてもらえますか?

テーブルは非常に単純で、それぞれにID列と他のいくつかの列がありますが、大量のテーブルがあり、そのすべてに、のような名前が付いています'TX-xxx'。ここで、'TX'はテキサスを意味'xxx'し、テキサスの郡です。テキサスには200以上の郡があります。(実際、私はすべての州に対してこれを行う必要があります。)したがって、ステートメントを使用したいと思います"LIKE 'TX-___'"

ありがとう!

4

3 に答える 3

5

必要な情報を正確に把握できるように、より多くの情報を提供する必要がありますが、ビューを作成することもできます

CREATE VIEW myViewName AS 

select * 
from table1 

union all 

select * from 
table2 

このようにして、すべてのテーブルからの情報が表示され(すべてを表示しないように選択で制限できます)、table1、table2などが変更されると、ビューにこれが反映されます。テーブルと同じように、いつでも変更してフェッチできます。

 select * from myViewName

特定のテーブルから取得するために、tsqlで実行しましたが、mysqlでこれを実行する方法がわかりません。この前の質問はあなたを助けるので、あなたは次のようなものを持っているかもしれません:

-- 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;
于 2012-05-23T17:03:56.580 に答える
2

私があなたの質問を正しく理解しているなら、UNIONはあなたが必要としているものです。何かのようなもの

SELECT field1, field2
FROM (
SELECT field1, field2 from table1
UNION
SELECT field1, field2 from table2
) all_tables
WHERE all_tables.field1 like "%whatever%
于 2012-05-23T17:03:13.497 に答える
0

それらが同じ列または類似のものを持っていると仮定します。

insert into #table
Select * from (Select * from tbl1 
               Union 
               select * from tbl2 
               Union 
               select * from tbl3)

同じ数/タイプの列がない場合は、その情報を提供する必要があります。

于 2012-05-23T18:41:41.853 に答える