2.6 KiB
2.6 KiB
数据库-1
#1 添加字段
ALTER TABLE t_customer ADD integral INT(10) DEFAULT 0;
#2 插入记录
INSERT INTO t_goods()
VALUES(10011, '口香糖', 2.5, 10, '零食');
#3 tj11 排序+分页+子查询查询
#先将第五个的库存数量查询出来 LIMIT 起始位置(从0开始), 取的个数;
SELECT g1.gname, g1.stock
FROM t_goods g1
WHERE g1.stock <= (
SELECT g2.stock
FROM t_goods g2
ORDER BY g2.stock
LIMIT 4, 1
)
ORDER BY g1.stock;
#4 tj12 子查询
SELECT g1.gname, g1.type, g1.price
FROM t_goods g1
WHERE g1.price = (
SELECT MIN(g2.price)
FROM t_goods g2
WHERE g2.type = g1.type
);
#5 tj13 分组查询
SELECT o.ono, g.gname, o.num * g.price, o.otime
FROM t_order o, t_goods g
WHERE o.gno = g.gno;
#6 tj14 排序查询+连接查询
SELECT c.cno, c.cname, o.ono, o.gno, o.num, o.otime
FROM t_customer c, t_order o
WHERE c.cno = o.cno AND c.cname = '龙睿'
ORDER BY o.otime DESC;
#7 排序查询+分组查询+连接查询
CREATE VIEW v_order AS
SELECT o.ono, c.cname, g.gname, o.num, o.otime
FROM t_customer c, t_order o, t_goods g
WHERE c.cno = o.cno AND o.gno = g.gno
ORDER BY o.otime DESC
LIMIT 49, 31;
#8 触发器
DELIMITER $$
DROP TRIGGER IF EXISTS tri_customerlog;
CREATE TRIGGER tri_customerlog
AFTER UPDATE ON t_customer
FOR EACH ROW
BEGIN
INSERT INTO t_log()
VALUES(DEFAULT, NEW.cno, '更新客户信息', '2024-06-06');
END $$
DELIMITER ;
#9 存储过程
DELIMITER $$
DROP PROCEDURE IF EXISTS pro_getSaleNumber;
CREATE PROCEDURE pro_getSaleNumber(IN in_gno CHAR(10), OUT out_number INT)
BEGIN
SELECT COUNT(DISTINCT cno) INTO out_number
FROM t_order
WHERE gno = in_gno;
END $$
DELIMITER ;
#测试
CALL pro_getSaleNumber(10001, @result);
SELECT @result;
数据库-2
#1 插入记录
INSERT INTO t_student()
VALUES(DEFAULT, '赵十', '男', 17, '10006');
#2 添加字段
ALTER TABLE t_student ADD notes VARCHAR(255);
#3 创建表
CREATE TABLE t_teacher(
tid CHAR(10) PRIMARY KEY,
tname VARCHAR(20) NOT NULL,
sex CHAR(2),
age INT(2),
subject VARCHAR(20),
salary DECIMAL(10, 2)
);
#4 设置薪资默认值
#ALTER TABLE 表名 ALTER 字段名 SET DEFAULT 默认值;
ALTER TABLE t_teacher ALTER salary SET DEFAULT 5000;
#5 插入记录
INSERT INTO t_teacher()
VALUES('t0001', '王老师', '男', 42, '数学', 6000);
#6 数据更新
UPDATE t_class c
SET c.address = '四层'
WHERE c.cname = '高三2班';
#7 tj11 条件查询
SELECT *
FROM t_student s
WHERE s.sex = '男';
#8 视图
CREATE VIEW v_class AS
SELECT c.cname, COUNT(IF(s.sex = '男', TRUE, NULL)), COUNT(IF(s.sex = '女', TRUE, NULL))
FROM t_student s, t_class c
WHERE s.cid = c.cid
GROUP BY c.cid;