SQL49 针对库中的所有表生成对应的SQL语句

本文最后更新于:2022年4月9日 中午


题目描述

针对库中的所有表生成select count(*)对应的SQL语句,如数据库里有以下表,

(注:在 SQLite 中用 “||” 符号连接字符串,无法使用concat函数)

employees

departments

dept_emp

dept_manage

salaries

titles

emp_bonus

那么就会输出以下的样子:

cnts
select count(*) from employees;
select count(*) from departments;
select count(*) from dept_emp;
select count(*) from dept_manager;
select count(*) from salaries;
select count(*) from titles;
select count(*) from emp_bonus;

输入描述

输出描述

题解

1
select "select count(*) from "||name||";" as cnts from sqlite_master where type='table';

备注:

  1. 在 SQLite 系统表 sqlite_master 中可以获得所有表的索引,其中字段 name 是所有表的名字,而且对于自己创建的表而言,字段 type 永远是 ‘table’;

  2. 在MySQL中可以:

    1
    2
    select concat("select count(*) from "," ",table_name,";") as cnts
    from (select table_name from information_schema.tables) as new;

参考文章:

参考 [20190521] 的解答

参考 [ciphersaw] 的解答