Mysql的查询、左连接查询手札

以前学习过的知识,许久不用都差不多忘记得七七八八了,今天想起来就突然记记。

很多事,不想不做就会忘记,人最怕的就是自己的价值被埋没了,2018将至,是结束也是开始。

shwo create table student;

CREATE TABLE `student` (
  `student_id` int(11) NOT NULL AUTO_INCREMENT,
  `student_name` varchar(255) DEFAULT NULL,
  `student_class` int(11) DEFAULT NULL,
  PRIMARY KEY (`student_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

add student data;

INSERT INTO `student` VALUES ('1', '张三', '801');
INSERT INTO `student` VALUES ('2', '李四', '802');
INSERT INTO `student` VALUES ('3', '王五', '803');
INSERT INTO `student` VALUES ('4', '赵六', '804');

show create table score;

CREATE TABLE `score` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `score` int(11) DEFAULT NULL,
  `student_id` int(11) DEFAULT NULL,
  `object` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

add score data;

INSERT INTO `score` VALUES ('1', '80', '1', '语文');
INSERT INTO `score` VALUES ('2', '90', '2', '语文');
INSERT INTO `score` VALUES ('3', '88', '3', '语文');
INSERT INTO `score` VALUES ('4', '99', '4', '数学');

show create table classname;

CREATE TABLE `classname` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_class` int(11) DEFAULT NULL,
  `class_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

add classname data;

INSERT INTO `classname` VALUES ('1', '801', '八年级一班');
INSERT INTO `classname` VALUES ('2', '802', '八年级二班');
INSERT INTO `classname` VALUES ('3', '803', '八年级三班');
INSERT INTO `classname` VALUES ('4', '804', '八年级四班');

sql query

select st.student_name as 学生名称 ,sc.object as 科目,sc.score as 分数 ,cname.class_name as 班级
from student st  //为了方便写sql查询语句,我们给student写一个别名叫st
left join score sc  //左连接表 score  这里我们也写一个别名叫 sc
on st.student_id=sc.student_id //重点,查询出左连接的查询依据就是 student 表里面的 student_id = 成绩表里面的 student_id
left join classname cname //此时我们把放班级名称的表的名字也用左连接查询查出来
on st.student_class=cname.student_class

效果图

左外连接是以左边的表(student st left)student为主表,score为从表。在查询结果中全部展示主表的信息。

Comments: 14

「人生在世,留句话给我吧」

提交评论