关系型数据库(八)SQL
多表关联因为大部分时候结果不在一张表中所以需要多表查询也称为关联查询指两个或更多个表一起完成查询操作。select a.student_name,b.score from student a,score b where a.student_no b.student_noa b是别名,让a表学生表的学号b表分数表的学号相等取出a表中的学生名字b表中的分数练习 将department 部门表和员工表employee表相关联查询结果显示员工名称员工年龄 部门id,部门名称内连接查询用左边表的记录去匹配右边表的记录如果符合条件的则显示。1.隐式内连接看不到 join 关键字条件使用where指定select 列名 from 左表 [左表别名], 右表 [右表别名] where 主表.主键从表.外键;相当于查询学生表,分数表的交集数据使用where条件消除无效数据字段要由对应的表名或别名调用。2.显示内连接使用 inner join ... on 语句可以省略 innerselect 列名 from 左表 inner join 右表 on 主表.主键从表.外键;、select * from student ainner joinscoreona.student_noscore.student_no;注意一般不用谢inner join 相当与外连接左外连接张三这个学生学号是4但是成绩表里没有学号4的成绩但是要求显示全部学生的名单和成绩怎么办select * fromstudenta left join score on a.student_noscore.student_no;特点需要指定一张查询主表查询主表的记录必须全部显示即使不符合表关联的条件左外连接查询的数据以左表为准即使在其他表中没有匹配的记录也会显示出来。使用 left outer join onouter可以省略相当于查询A表所有数据和交集部分数据select 列名 from 左表 left join 右表 on 表连接条件右外连接右外连接查询的数据以右表为准即使在其他表中没有匹配的记录也会显示出来。使用right join ... on下面这个例子用来显示所有有成绩的学生名单没有成绩的将不显示select * from student aright joinscore on a.student_noscore.student_no;update 更新语句UPDATE 表名 SET 列名表达式列名表达式 [WHERE 条件]update 表名 set 字段名值;updatestudentsetstudent_name王刚1wherestudent_no1练习 部门表department 名称为销售部的money改为1200插入语句 insert语法insert into 数据表名字段字段字段 values (值值值);insert into 数据表名 value值值值;insert into student (student_no) values (8)insert into student (student_no,student_name) values (9,李四)练习使用insert 语句给department查入一条数据删除语句DELETE FROM 表名 [ WHERE 条件]delete from student where student_name 李四删除employee中id为5的记录创建表根据已有的表创建新表1.create table tab_new like tab_old (使用旧表创建新表)create table student1 like student2.create table tab_new as select col1,col2… from tab_oldcreate table tab_new as select student_no from studentcreate table student1(id int,name char(10),age int,sex char(5));数据表添加列alter table student1 add height int(10);数据表删除列alter table student1 drop height;数据列修改数据类型alter table student modify column high char(10);修改表名alter table student1 rename to student_table;删除新表drop table tabnamedrop table tab_new创建数据库CREATE TABLEstudents33 (id INT PRIMARY KEY,name VARCHAR(32),age INT,gender VARCHAR(16));子查询多表查询SELECT子查询子查询可以作为SELECT语句的一部分用于在查询结果中生成一个或多个列SELECT column1, column2, (SELECT COUNT(*) FROM table2) AS count FROM table1;SELECT student_no, student_name, (SELECT COUNT(*) FROM student) AS count FROM student;FROM子查询子查询可以作为FROM子句的一部分用于在外部查询中引用一个虚拟表SELECT * FROM (SELECT column1, column2 FROM table1) AS subquery;SELECT * FROM (SELECT student_name FROM student) AS subquery;INSERT子查询子查询可以作为INSERT语句的一部分用于将子查询的结果插入到目标表中INSERT INTO table1 (column1, column2) SELECT column1, column2 FROM table2;