mysql视图的综合运用(实例)

1.创建表,插入数据


SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for sign
-- ----------------------------
DROP TABLE IF EXISTS `sign`;
CREATE TABLE `sign` (
  `s_id` int(11) NOT NULL,
  `s_name` varchar(20) DEFAULT NULL,
  `s_sch` varchar(20) DEFAULT NULL,
  `s_sign_sch` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`s_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sign
-- ----------------------------
INSERT INTO `sign` VALUES ('1', 'xiaowang', 'schoo1', 'Peking');
INSERT INTO `sign` VALUES ('2', 'xiaoli', 'schoo2', 'Tsinghua');
INSERT INTO `sign` VALUES ('3', 'xiaotian', 'schoo3', 'Tsinghua');

-- ----------------------------
-- Table structure for stu
-- ----------------------------
DROP TABLE IF EXISTS `stu`;
CREATE TABLE `stu` (
  `s_id` int(11) NOT NULL,
  `s_name` varchar(20) DEFAULT NULL,
  `addr` varchar(20) DEFAULT NULL,
  `tel` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`s_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of stu
-- ----------------------------
INSERT INTO `stu` VALUES ('1', 'xiaowang', 'henan', '1234');
INSERT INTO `stu` VALUES ('2', 'xiaoli', 'hebei', '2345');
INSERT INTO `stu` VALUES ('3', 'xiaotian', 'beijing', '3456');

-- ----------------------------
-- Table structure for stu_mark
-- ----------------------------
DROP TABLE IF EXISTS `stu_mark`;
CREATE TABLE `stu_mark` (
  `s_id` int(11) NOT NULL,
  `s_name` varchar(20) NOT NULL,
  `mark` int(11) NOT NULL,
  PRIMARY KEY (`s_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of stu_mark
-- ----------------------------
INSERT INTO `stu_mark` VALUES ('1', 'xiaowang', '80');
INSERT INTO `stu_mark` VALUES ('2', 'xiaoli', '71');
INSERT INTO `stu_mark` VALUES ('3', 'xiaotian', '70');

2.创建视图


-- ----------------------------
-- View structure for beida
-- ----------------------------
DROP VIEW IF EXISTS `beida`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `beida` AS select `stu_mark`.`s_id` AS `s_id`,`stu_mark`.`s_name` AS `s_name`,`stu_mark`.`mark` AS `mark`,`sign`.`s_sign_sch` AS `s_sign_sch` from (`stu_mark` join `sign`) where ((`stu_mark`.`s_id` = `sign`.`s_id`) and (`stu_mark`.`mark` >= 1) and (`sign`.`s_sign_sch` = 'Peking')) ;

-- ----------------------------
-- View structure for qinghua
-- ----------------------------
DROP VIEW IF EXISTS `qinghua`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `qinghua` AS select `stu_mark`.`s_id` AS `s_id`,`stu_mark`.`s_name` AS `s_name`,`stu_mark`.`mark` AS `mark`,`sign`.`s_sign_sch` AS `s_sign_sch` from (`stu_mark` join `sign`) where ((`stu_mark`.`s_id` = `sign`.`s_id`) and (`stu_mark`.`mark` > 70) and (`sign`.`s_sign_sch` = 'Tsinghua')) ;
SET FOREIGN_KEY_CHECKS=1;

3.效果展示
view1
view2

你可能感兴趣的:(mysql)