drop table可以删除多张表吗_MySQL DROP TABLE语句删除表

Summary: in this tutorial, we will show you how to remove existing tables using the MySQL DROP TABLE statement.

MySQL DROP TABLE statement syntax

In order to remove existing tables, you use the MySQL DROP TABLE statement. The syntax of the DROP TABLE is as follows:DROP [TEMPORARY] TABLE [IF EXISTS] table_name [, table_name] ... [RESTRICT | CASCADE]

The DROP TABLE statement removes a table and its data permanently from the database. In MySQL, you can also remove multiple tables using a single DROP TABLE statement, each table is separated by a comma (,).

The TEMPORARYflag allows you to remove temporary tables only. It is very convenient to ensure that you do not accidentally remove non-temporary tables.

The IF EXISTS addition allows you to hide the error message in case one or more tables in the list do not exist. When you use IF EXISTS addition, MySQL generates a NOTE, which can be retrieved by using the SHOW WARNINGstatement. It is important to notice that the DROP TABLE statement removes all existing tables and issues an error message or a NOTE when you have a non-existent table in the list.

As mentioned above, the DROP TABLE statement only removes table and its data. However, it does not remove specific user privileges associated with the table. Therefore if a table with the same name is re-created after that, the existing privileges will apply to the new table, which may pose a security risk.

The RESTRICT and CASCADEflags are reserved for the future versions of MySQL.

Last but not least, you must have DROP privileges for the table that you want to remove.

MySQL DROP TABLE example

We are going to remove the taskstable that we created in the previous tutorial on creating tables using CREATE TABLE statement. In addition, we also remove a non-existent table to practice with the SHOW WARNING statement. The statement to remove the tasks table and a non-existent table is as follows:DROP TABLE IF EXISTS tasks, nonexistent_table;

If you check the database, you will see that the taskstable was removed. You can check the NOTE, which is generated by MySQL because of non-existent table, by using the SHOW WARNING statement as follows:SHOW WARNINGS;

AAffA0nNPuCLAAAAAElFTkSuQmCC

MySQL DROP TABLE LIKE

Image you have a lot of tables whose names start with testin your database and you want to save time by removing all of them using a single DROP TABLE statement. Unfortunately, MySQL does not provide the DROP TABLE LIKE statement that can remove tables based on pattern matching like the following:DROP TABLE LIKE '%pattern%'

However, there are some workarounds. We will discuss one of them here for your reference.

Let’s start creating test* tables for the sake of demonstration.CREATE TABLE IF NOT EXISTS test1(   id int(11) NOT NULL AUTO_INCREMENT,   PRIMARY KEY(id) ); CREATE TABLE IF NOT EXISTS test2 LIKE test1; CREATE TABLE IF NOT EXISTS test3 LIKE test1; CREATE TABLE IF NOT EXISTS test4 LIKE test1;

We’ve created four tables named test1, test2, test3and test4with the same table structure.

Suppose you want to remove all test* tables at a time, you can follow the steps below:

First, you declare two variables that accept database schema and a pattern that you want to the tables to match:-- set table schema and pattern matching for tables SET @schema = 'classicmodels'; SET @pattern = 'test%';

Next, you need to build a dynamic DROP TABLE statement:-- build dynamic sql (DROP TABLE tbl1, tbl2...;) SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';') INTO @droplike FROM information_schema.tables WHERE @schema = database() AND table_name LIKE @pattern;

Basically, the query instructs MySQL to go to the information_schematable, which contains data on all tables in all databases, and to concatenate all tables in the database @schema( classicmodels)that matches the pattern @pattern ( test%)with the prefix DROP TABLE.The GROUP_CONCAT function creates a comma-separated list of tables.

Then, we can display the dynamic SQL to verify if it works correctly:-- display the dynamic sql statement SELECT @droplike;

AAffA0nNPuCLAAAAAElFTkSuQmCC

You can see that it works as expected.

After that, you can execute the statement using prepared statement in MySQL as follows:-- execute dynamic sql PREPARE stmt FROM @dropcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt;

For more information on MySQL prepared statement, check it out the MySQL prepared statement tutorial.

Putting it all together.-- set table schema and pattern matching for tables SET @schema = 'classicmodels'; SET @pattern = 'test%'; -- build dynamic sql (DROP TABLE tbl1, tbl2...;) SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';') INTO @droplike FROM information_schema.tables WHERE @schema = database() AND table_name LIKE @pattern; -- display the dynamic sql statement SELECT @droplike; -- execute dynamic sql PREPARE stmt FROM @dropcmd; EXECUTE stmt; DEALLOCATE PREPARE stmt;

So if you want to drop multiple tables that have a specific pattern in a database, you just use the script above to save time. All you need to do is replacing the pattern and thedatabase schema in @pattern and @schemavariables. If you often have to deal with this task, you can always develop a stored procedure based on the script and reuse the stored procedure in the future.

In this tutorial, we’ve shown you how to use the DROP TABLE statement to remove existing tables in a particular database. We also discussed about a workaround that allows you to use the DROP TABLE statement to remove tables based on pattern matching.

Related Tutorials

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常感谢您的提问!如果您想要在Flink中获取MySQL张表的信息,可以按照如下步骤进行: 1. 首先需要在Flink中使用JDBC连接器连接MySQL数据库,并创建一个JDBC输入源,以便从MySQL中读取数据。 2. 然后可以通过Flink的Table API或SQL API将多张表的数据进行连接或者关联,从而得到您需要的数据。 3. 最后可以使用自定义的Sink将数据写入MySQL中。下面就是一个简单的Java代码示例,可以帮助您实现该功能: ``` public class FlinkMySQLSink { public static void main(String[] args) throws Exception { // set up the execution environment StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // set up JDBC connection options String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "password"; String driverName = "com.mysql.jdbc.Driver"; // create a JDBC input source to read multiple tables from MySQL JdbcInputFormat jdbcInputFormat = JdbcInputFormat.buildJdbcInputFormat() .setDrivername(driverName) .setDBUrl(url) .setUsername(username) .setPassword(password) .setQuery("SELECT * FROM table1; SELECT * FROM table2;") .finish(); // create a data stream from the JDBC input source DataStream<Tuple2<String, String>> inputDataStream = env.createInput(jdbcInputFormat); // use Table API or SQL API to join or combine multiple tables Table table = inputDataStream .map(new MapFunction<Tuple2<String, String>, Row>() { public Row map(Tuple2<String, String> value) throws Exception { return Row.of(value.f0, value.f1); } }) .toTable(new TableSchema(new String[]{"column1", "column2"}, new TypeInformation[]{Types.STRING, Types.STRING})); // create a custom Sink to write data back to MySQL JDBCOutputFormat jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername(driverName) .setDBUrl(url) .setUsername(username) .setPassword(password) .setQuery("INSERT INTO result_table (column1, column2) VALUES (?, ?)") .finish(); // write the data stream to the custom Sink table.writeToSink(jdbcOutputFormat); // execute the Flink job env.execute("Flink MySQL Sink Example"); } } ``` 在这个示例中,我们首先设置了JDBC连接器所需的参数,然后使用JdbcInputFormat创建了一个JDBC输入源,该源可以从MySQL中读取多个表的数据。 接下来,我们使用Table API或SQL API将多个表的数据连接或者关联起来,并生成一个包含所需数据的Table对象。 最后,我们使用自定义的JDBCOutputFormat创建一个Sink,将Table中的数据写回到MySQL中。在这个Sink中,我们需要指定要写入哪个表,以及如何将数据映射到表中的列。 希望这个示例可以帮助您实现获取MySQL张表信息的功能!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值