【基础篇】操作数据表
1.创建表:create table 【表名】(列名1 属性, 列名2 属性 ...);
CREATE TABLE tb_admin (
id INT auto_increment PRIMARY KEY,
USER VARCHAR (30) NOT NULL,
PASSWORD VARCHAR (100) NOT NULL,
createtime datetime
);
2.查看表:describe desc【表名】;
DESC tb_admin DESCRIBE tb_admin;
3.查看列:describe desc【列名】;
DESC tb_admin id DESCRIBE tb_admin id;
4. 修改表:修改多项时用逗号连接;
ALTER TABLE tb_admin ADD number VARCHAR (100) AFTER id; //新增字段名
ALTER TABLE tb_admin MODIFY USER VARCHAR (200); //修改字段定义
ALTER TABLE tb_admin CHANGE COLUMN USER username VARCHAR (100) NOT NULL; //修改字段名
ALTER TABLE tb_admin DROP age; //删除字段
ALTER TABLE tb_admin RENAME admin; //重命名表方式一
RENAME TABLE tb_admin1 TO admin1; //重命名表方式二
CREATE TABLE admin_bk LIKE admin; //复制表(只复制表结构,不带有数据)
CREATE TABLE admin_new AS SELECT * FROM admin; //复制表(复制表结构和数据)
DROP TABLE IF EXISTS admin_bk; //删除表(加入 if exists 避免删除一个不存在的表 从而导致错误)
【基础篇】流程控制语句:与一般程序设计所不同的是,存储过程并不支持FOR循环
1. IF语句:
CREATE PROCEDURE example_if (IN x INT)
BEGIN
IF x = 1 THEN SELECT 1;
ELSEIF x = 2 THEN SELECT 2;
ELSE SELECT 3;
END IF;
END;
调用该存储过程:CALL example_if (3);
2. CASE语句:
CREATE PROCEDURE example_case (IN x INT)
BEGIN
CASE x
WHEN 1 THEN SELECT 1;
WHEN 2 THEN SELECT 2;
ELSE SELECT 3;
END CASE;
END;
调用该存储过程:CALL example_if (3);
3. WHILE循环语句:求前100项的和
CREATE PROCEDURE example_while (OUT sum INT)
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE s INT DEFAULT 0;
WHILE i <= 100 DO
SET s = s + i;
SET i = i + 1;
END WHILE;
SET sum = s;
END;
调用该存储过程:CALL example_while(@s); SELECT@s;
4. LOOP循环语句:求前100项的和
CREATE PROCEDURE example_loop (OUT sum INT)
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE s INT DEFAULT 0;
loop_lable:LOOP
SET s = s + i;
SET i = i + 1;
IF i > 10 THEN
LEAVE loop_lable;
END IF;
END LOOP;
SET sum = s;
END;
调用该存储过程:CALL example_loop(@s); SELECT@s;
5. REPEAT循环语句:求前100项的和
CREATE PROCEDURE example_repeat (OUT sum INT)
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE s INT DEFAULT 0;
REPEAT
SET s = s + i;
SET i = i + 1;
UNTIL i > 100
END REPEAT;
SET sum = s;
END;
调用该存储过程:CALL example_repeat(@s); SELECT@s;
【基础篇】数据表的增删改查
1. INSERT VALUES
1.1 插入全部数据
INSERT INTO tb_admin VALUES ('2','名字','学历',' 年龄','邮箱');
1.2 插入部分数据
INSERT INTO tb_admin (username, emile) VALUES ('名字','qq.com');
1.3 插入多条数据
INSERT INTO tb_admin (
username,
PASSWORD,
createtime,
emile
)
VALUES
('赵', '1', '2020', 'qq.com'),
('赵', '1', '2020', 'qq.com');
2. INSET SET
INSERT INTO tb_admin SET username = '钱'
3. INSERT SELECT :插入查询结果
INSERT INTO tb_admin11 (
id,
username,
PASSWORD,
createtime,
emile
) SELECT
*
FROM
tb_admin;
4.变更字段值
update 表名 SET `字段` = REPLACE(`字段`,'旧值','新值')