在MySQL中加入两个查询以将一个查询的结果映射到另一个查询

时间:2017-06-07 21:35:48

标签: mysql sql join

我在MYSQL中有如下查询。此查询为我提供了表名列表,列名中没有特定的特殊字符。

select distinct A.table_name from (select TABLE_NAME from information_schema.columns where TABLE_SCHEMA = 'testing' order by TABLE_NAME) A LEFT JOIN 
(select table_name from information_schema.columns where (COLUMN_NAME like '% %' or COLUMN_NAME like '%{%' or COLUMN_NAME like '%(%' or COLUMN_NAME like '%;%' 
or COLUMN_NAME like '%.%') and TABLE_SCHEMA = 'testing' order by TABLE_NAME) B ON (A.TABLE_NAME=B.TABLE_NAME) where B.table_name IS NULL 

以上查询的结果:

100_test
101_test
102_backup
103_backup

我还有另一个查询,如下所示:

select src_table,dst_table from test.mapping

此处test是数据库,mapping是表名。

结果:

100_test    100_testing
101_test    101_testing
102_backup  102_backup_old
103_backup  103_backup_old
105_old_test    105_archived

现在我想创建一个查询,为test.mapping查询结果的每个表提供1st的src_table和dst_table。

我想将两个查询作为单个查询加入,这样可以得到如下结果

100_test    100_testing
101_test    101_testing
102_backup  102_backup_old
103_backup  103_backup_old

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

select src_table,dst_table from test.mapping
where src_table in 
(
select distinct A.table_name from (select TABLE_NAME from information_schema.columns where TABLE_SCHEMA = 'testing' order by TABLE_NAME) A LEFT JOIN 
(select table_name from information_schema.columns where (COLUMN_NAME like '% %' or COLUMN_NAME like '%{%' or COLUMN_NAME like '%(%' or COLUMN_NAME like '%;%' 
or COLUMN_NAME like '%.%') and TABLE_SCHEMA = 'testing' order by TABLE_NAME) B ON (A.TABLE_NAME=B.TABLE_NAME) where B.table_name IS NULL 
)