您可以使用存储过程在单个查询中插入两个表中。让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20) );
这是创建第二个表的查询-
mysql> create table DemoTable2 ( ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(20), ClientAge int );
以下是创建存储过程的查询,以插入到上面创建的两个表中-
mysql> DELIMITER // mysql> CREATE PROCEDURE insert_into_twoTables(name varchar(100),age int) BEGIN INSERT INTO DemoTable(StudentFirstName) VALUES(name); INSERT INTO DemoTable2(ClientName,ClientAge) VALUES(name,age); END // mysql> DELIMITER ;
现在借助CALL命令调用存储过程-
mysql> call insert_into_twoTables('Tom',38);
检查记录是否插入到两个表中。
显示第一张表中所有记录的查询如下-
mysql> select * from DemoTable;
这将产生以下输出-
+-----------+------------------+ | StudentId | StudentFirstName | +-----------+------------------+ | 1 | Tom | +-----------+------------------+ 1 row in set (0.00 sec)
以下是显示第二个表中所有记录的查询-
mysql> select * from DemoTable2;
这将产生以下输出-
+----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 1 | Tom | 38 | +----------+------------+-----------+ 1 row in set (0.00 sec)