简体   繁体   English

MySQL合并多个表中的行

[英]mysql merge rows from multiple tables

I have a mysql database that contains multiple tables with the same columns (not my design decision). 我有一个mysql数据库,其中包含具有相同列的多个表(不是我的设计决定)。 These tables are named dynamically like codes_1, codes_2.... I would like to execute a query that will take the contents (rows) of codes_1, and codes_2..., and merge them together into one result. 这些的动态命名类似于code_1,code_2....。我想执行一个查询,该查询将采用code_1和code_2 ...的内容(行),并将它们合并为一个结果。

I already have sql that can return the names of the tables using SCHEMA_INFORMATION.table_name, but I cannot figure out how to query each table based on the name, and how to merge the result of each table into one result. 我已经有了可以使用SCHEMA_INFORMATION.table_name返回表名的sql,但是我无法弄清楚如何根据名称查询每个表,以及如何将每个表的结果合并为一个结果。

So in reality here are the two questions: 所以实际上这是两个问题:

  1. how can I query multiple tables based on the table names that are returned as a query result? 如何根据作为查询结果返回的表名查询多个表?

  2. how can I, after doing a select on each table, merge all the rows from the tables into one result? 在对每个表进行选择后,如何将表中的所有行合并为一个结果?

Is this what you're looking for? 这是您要找的东西吗? Edit the colums to your preference, you never specified your table names so I just named them table_1 and table_2. 根据您的喜好编辑列,您从未指定表名,所以我只将它们命名为table_1和table_2。

SELECT codes_1, codes_2, codes_3 FROM `table_1`
UNION 
SELECT codes_1, codes_2, codes_3 FROM `table_2`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM