迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 数据库 > MySQL >

在 MySQL 中插入多个表

作者:迹忆客 最近更新:2023/05/07 浏览次数:

本篇文章将介绍在 MySQL 中插入多个表的事务和存储过程。


在 MySQL 中插入多个表

无法将单个MySQL命令插入到多个表中,但是我们可以使用MySQL事务来满足项目需求。

让我们创建两个名为 users 和 user_profiles 的表。 users 表具有三个属性,user_id、user_name 和 user_password,而 profiles 表包含 user_id、user_bio 和 homepage 作为属性。

请参阅我们用于创建这两个表的以下命令。

示例代码:

CREATE TABLE users(
    user_id INT NOT NULL AUTO_INCREMENT,
    user_name VARCHAR(45) NOT NULL,
    user_password VARCHAR(45) NOT NULL,
    PRIMARY KEY(user_id)
);

CREATE TABLE user_profiles(
    user_id VARCHAR(45) NOT NULL,
    user_bio VARCHAR(45) NOT NULL,
    homepage VARCHAR(50) NOT NULL
);

在这里,我们已经创建了两个表。 现在,我们可以通过以下方式同时向两个表中插入数据。

请记住,user_profiles.user_idusers.user_id 的值是相同的。

示例代码:

BEGIN;
    INSERT INTO users (user_id,user_name, user_password)
    VALUES (2,'username2', 'userpassword2');
    SELECT @UserID := MAX(user_id) FROM users;
    INSERT INTO user_profiles (user_id, user_bio, homepage)
    VALUES(@UserID,'this is bio for username2', 'http://www.username2.com');
COMMIT;

添加两条记录并使用 SELECT 语句查看结果。

输出( users 表):

+---------+-----------+---------------+
| user_id | user_name | user_password |
+---------+-----------+---------------+
|       1 | username1 | userpassword1 |
|       2 | username2 | userpassword2 |
+---------+-----------+---------------+
2 rows in set (0.03 sec)

输出( user_profiles 表):

+---------+---------------------------+--------------------------+
| user_id | user_bio                  | homepage                 |
+---------+---------------------------+--------------------------+
| 1       | this is bio for username1 | http://www.username1.com |
| 2       | this is bio for username2 | http://www.username2.com |
+---------+---------------------------+--------------------------+
2 rows in set (0.00 sec)

或者,我们可以创建一个存储过程如下,以节省时间和精力。

示例代码:

DELIMITER ;;

CREATE PROCEDURE InsertALL()
BEGIN
    INSERT INTO users (user_id,user_name, user_password)
    VALUES (3,'username3', 'userpassword3');
    SELECT @UserID := MAX(user_id) FROM users;
    INSERT INTO user_profiles (user_id, user_bio, homepage)
    VALUES(@UserID,'this is bio for username3', 'http://www.username3.com');
END ;;

DELIMITER ;

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

如何在 MySQL 中声明和使用变量

发布时间:2024/03/26 浏览次数:115 分类:MySQL

当你需要在 MySQL 中的脚本中存储单个值时,最好的方法是使用变量。变量有不同的种类,有必要知道何时以及如何使用每种类型。

在 MySQL 中实现刷新权限

发布时间:2024/03/26 浏览次数:211 分类:MySQL

本教程介绍了 MySQL 中的刷新权限命令,用于刷新授权表并影响允许的更改。

在 MySQL 中设置时区

发布时间:2024/03/26 浏览次数:93 分类:MySQL

在本教程中,我们将学习如何在 MySQL 服务器中更改时区。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便