数据库

什么是数据库 存储数据的仓库,本质上是一套CS结构的软件程序,分为客户端和服务器, 我们通常说安装数据,装的其实是服务器

库的语句

create database

drop database

alter database

show databases

show create database

表的语句

create table

drop table

alter table add|modify|drop |change

show tables

show create table

desc 表名

rename table a to b

记录的操作

insert into

delete from table

truncate table

update 表名 set xx = xx

select * from 表名

数据类型

int float

char varchar text blob enum set

year date time datetime timestamp

约束

unsigned

unique

not null

null

default

primary key auto_increment

foreign key

添加数据补充:

将一个查询结果插入到另一张表中

create table student(name char(10),gender int);

insert into student values("jack",1);

insert into student values("rose",0);

create table student_man(name char(10),gender int);

insert into student_man select * from student where gender = 1;

多表查询

select * from table1,table2,......

# 笛卡尔积查询的结果会出现大量的错误数据即,数据关联关系错误!

添加过滤条件 从表外键值 等于 主表的主键值

# 并且会产生重复的字段信息 例如员工里的 部门编号 和 部门表的id字段

在select 后指定需要查询的字段名称

案例:

select dept.name 部门 ,dept.id 部门编号,emp.name 姓名,emp.id 员工编号,sex from emp ,dept where dept.id = dept_id;

多表查询案例:

create table stu(id int primary key auto_increment,name char(10));

create table tea(id int primary key auto_increment,name char(10));

create table tsr(id int primary key auto_increment,t_id int,s_id int,

foreign key(s_id) references stu(id),

foreign key(t_id) references tea(id));

insert into stu values(null,"张三"),(null,"李四");

insert into tea values(null,"egon"),(null,"wer");

insert into tsr values(null,1,1),(null,1,2),(null,2,2);

#egon老师教过哪些人?

select tea.name,stu.name from tea join tsr join stu

on

tea.id = t_id and stu.id = s_id

where tea.name = "egon";

# 子查询实现

select * from stu where id in (select s_id from tsr where t_id = (select id from tea where name = "egon"));

内连接查询:

本质上就是笛卡尔积查询

语法:

select * from table1 inner join table2;

案例:

select * from emp inner join dept where dept_id = dept.id;

inner可以省略

select * from emp join dept where dept_id = dept.id;

左外连接查询

左边的表无论是否能够匹配都要完整显示

右边的仅展示匹配上的记录

需求: 要查询所有员工以及其所属的部门信息

select * from emp left join dept on dept_id = dept.id;

注意: 在外连接查询中不能使用where 关键字 必须使用on专门来做表的对应关系

右外连接查询

右边的表无论是否能够匹配都要完整显示

左边的仅展示匹配上的记录

需求: 要查询所有部门以及其对应的员工信息

select * from emp right join dept on dept_id = dept.id;

全外连接查询

无论是否匹配成功 两边表的数据都要全部显示

需求:查询所有员工与所有部门的对应关系

select * from emp full join dept on dept_id = dept.id;

注意:mysql不支持全外连接

我们可以将 左外连接查询的结果 和 右外连接查询的结果 做一个合并

select * from emp left join dept on dept_id = dept.id

union

select * from emp right join dept on dept_id = dept.id;

union的用法:

select * from emp

union

select * from emp;

# union将自动去除重复的记录

# union all 不去重复

select sex,name from emp

union

select * from dept;

# 注意 union 必须保证两个查询结果 列数相同 一般用在多个结果结构完全一致时

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐