我们可以在show语句中使用concat()group_concat()等函数吗?

时间:2016-04-06 08:31:16

标签: mysql show concat group-concat

例如我运行命令

的MySQL> show tables;

DB中的表

B'/ P>

C

d

我想使用它,例如concat(' drop table',tablename,';');

这样我的结果集就会变成

drop table a;

drop table b;

drop table c;

依旧......

2 个答案:

答案 0 :(得分:3)

使用21.24 The INFORMATION_SCHEMA TABLES Table

尝试:

SELECT
  CONCAT('drop table ', `TABLE_NAME`, ';')
FROM
  `INFORMATION_SCHEMA`.`TABLES`
WHERE
  `TABLE_SCHEMA` = DATABASE() AND
  `TABLE_TYPE` = 'BASE TABLE';

SQL Fiddle demo

答案 1 :(得分:0)

只需添加,如果要生成数据库列表,则使用类似以下内容的

SELECT CONCAT('DROP DATABASE `', `table_schema`, '`;') FROM (
    SELECT `table_schema`
    FROM `INFORMATION_SCHEMA`.tables
    WHERE `table_schema` != "INFORMATION_SCHEMA" && `table_schema` != "performance_schema"
    GROUP BY `table_schema`
) as dbs

此外,如果您希望将所有删除数据库查询都放在一行中,请使用GROUP_CONCAT

SELECT GROUP_CONCAT(ts SEPARATOR ' ') as drop_databases_query FROM (SELECT CONCAT('DROP DATABASE `', `table_schema`, '`;') as ts FROM (
    SELECT `table_schema`
    FROM `INFORMATION_SCHEMA`.tables
    WHERE `table_schema` != "INFORMATION_SCHEMA" && `table_schema` != "performance_schema"
    GROUP BY `table_schema`
) as dbs) as concatted

这将导致类似

DROP DATABASE `mydb`; DROP DATABASE `mydb2`; DROP DATABASE `mysql`; DROP DATABASE `sys`;