mysql 视图使用
视图是由一个或多个基础表(或视图)产生的虚拟表,数据库里存放了视图的定义,对应的数据是存放在物理数据表中。
使用视图有时可以简化用户操作,尤其是在需要关联多表查询时,不用关心视图查询的内部结构,只关注在索要获取的数据上
语法格式如下:
CREATE VIEW <视图名> AS <SELECT语句>
语法说明如下。
<视图名>
:指定视图的名称。该名称在数据库中必须是唯一的,不能与其他表或视图同名。<SELECT语句>
:指定创建视图的 SELECT 语句,可用于查询多个基础表或源视图。
1、准备工作
订单表:
DROP TABLE IF EXISTS `t_order`; CREATE TABLE `t_order` ( `id` int(11) NOT NULL AUTO_INCREMENT , `user_id` int(11) NOT NULL , `order_time` int(10) NOT NULL , `fee` int(11) NOT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci;
订单详情表:
DROP TABLE IF EXISTS `t_order_detail`; CREATE TABLE `t_order_detail` ( `id` int(11) NOT NULL AUTO_INCREMENT , `goods_id` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , `count` int(11) NOT NULL , `order_id` int(11) NOT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci;
商品表:
DROP TABLE IF EXISTS `t_goods`; CREATE TABLE `t_goods` ( `id` int(11) NOT NULL AUTO_INCREMENT , `good_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , `price` int(11) NOT NULL , `stock` int(11) NOT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci;
初始化测试数据:
INSERT INTO `t_goods` VALUES ('1', 'a', '12', '100'), ('2', 'b', '1', '100'); INSERT INTO `t_order` VALUES ('1', '1', '20190912', '1000000'); INSERT INTO `t_order_detail` VALUES ('1', '1', '10', '1'), ('2', '2', '5', '1');
2、创建视图
CREATE VIEW order_detail_2 (id, user_id, goods_name, goods_price, count, fee) AS SELECT o.id, o.user_id, tg.good_name, tg.price, tod.count, (tg.price * tod.count) FROM t_order o RIGHT JOIN t_order_detail tod ON o.id = tod.order_id RIGHT JOIN t_goods tg ON tod.goods_id = tg.id WHERE o.id = 1;
该视图是查询订单号为1的详细信息,之后就可以直接使用视图来查询了,查询过程就和基础表一样
SELECT * from order_detail;
3、可以写个存储过程来添加数据
BEGIN DECLARE i int default 0; DECLARE y int default 0; DECLARE order_id INT; DECLARE goods_id INT; # 子订单数量 DECLARE sub_order_count INT DEFAULT 1; # order_count为插入订单的数量控制,如果传入为null或者0时处理成0 IF order_count IS NULL OR order_count = 0 THEN SET order_count = 1; END IF; WHILE i < order_count DO # 插入订单表 INSERT INTO t_order(user_id, order_time) VALUES(00001,20190912); # 查询订单表最大的id SELECT MAX(id) INTO order_id FROM t_order; # 最多购买5件 SELECT ROUND(RAND() * 5) INTO sub_order_count; WHILE y < sub_order_count DO # 商品id随机获取,ROUND是四舍五入,RAND是[0,1)的取值 SELECT t1.id INTO goods_id FROM t_goods t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) from t_goods) - (SELECT MIN(id) from t_goods)) + (SELECT MIN(id) from t_goods)) AS goods_id) AS t2 ON t1.id >= t2.goods_id ORDER BY t1.id LIMIT 1; # 插入订单详情表 INSERT INTO t_order_detail(order_id, goods_id, count) VALUES(order_id, goods_id, 1); SET y = y + 1; END WHILE; # 清空订单详情的遍历标识 SET y = 0; SET i = i + 1; END WHILE; END
之后就可以通过调用来插入一些测试数据了,传入order_count
CALL add_while(10);