#0数据库级,增删改查
#创建数据库
create database if not exists 数据库名;#myschool;
#删除数据库
drop database if exists 数据库名;#myschool;
#修改数据库
#这个操作不能随意,就像是word打开了不能直接右键文件重命名
use test1;
alter database test1 set test2;#8.0版本,非此语法 FIXME bug
#查看数据库
show databases;
#使用数据库
use 数据库名;#myschool;
#1表级,增删改查
#创建表
create table 表名(
字段1,
字段2 comment '字段级解释',
字段3#这里不能有,
)comment='表级解释';
#删除表,先删有引用外键操作的表
drop table if exists 表名;
#修改表
alter table 旧表名 rename as 新表名;
#查看表
desc 表名;
#显示表创建语句
show create table 表名;#创建子表的两种方式
#方式一:根据select的结果创建表
drop table if exists phoneList;
create table if not exists phoneList(
select studentname,phone from student);
#方式二:表结构首先要建好,使用insert into...select
drop table if exists 表名;
create table 表名
(
字段1,
字段2
);
insert into 表名(字段名1,字段名2)
select 字段名1,字段名2 from 表名;
#2表内操作,字段,表创建语句内。增删改查
/*增加字段*/
字段名 int primary key auto_increment not null
/*添加字段*/
alter table 表名 add 字段名
varchar(20) not null;
/*删除字段*/
#字段
alter table 表名 drop 字段名;
/*修改字段*/
#名字
#略,不知#增加记录
#两种#1(union:联合,这是一个标准sql语句)
insert into 表名
(字段名s)#除了自动增长的字段auto_increment
select 值1s from 表名 union
select 值2s;#2
insert into 表名
(字段名s)#除了自动增长的字段auto_increment
values(值1,值2,...);#删某些记录
delete from 表名 where 条件;delete from 表名 等同于 truncate 表名
#修改值,某些值 指定的
update 表名 set 字段1=值1 where 条件;
/*查找*/
select 字段 from 表名;#char(6) 'hello ' 固定长度
#varchar(6) 'hello' 可变长度
#主键
#表创建语句内
字段名 类型 primary key
或primary key(字段名1,字段名2,...)
#外键
#表创建语句内 constraint约束
constraint fk_引用表_当前表 foreign key(字段名)#该字段被选为外键,fk_引用表_当前表为外键名
references 引用表(引用表)
#原则一般是引用的他表的主键,非当前表主键
#语句外
#主键,复合主键
alter table 当前表名 add constraint pk_表名 primary key(字段名1,字段名2,...);
#外键
alter table 当前表名 add constraint fk_引用表_当前表 foreign key(字段名)#该字段被选为外键,fk_引用表_当前表为外键名
references 引用表(引用表);
例子:
-- Score(s_id,c_id,s_score)
-- 学生编号,课程编号,分数
CREATE TABLE `Score`(
`s_id` VARCHAR(20),
`c_id` VARCHAR(20),
`s_score` INT(3),
PRIMARY KEY(`s_id`,`c_id`)
)
SQL外键约束可通过FOREIGN KEY关键字来指定,创建语句为“ALTER TABLE 表名 ADD CONSTRAINT 外键名 FOREIGN KEY(列名) REFERENCES 主表名 (列名);”。
Java中:
1、对象的内容不同 null表示对象的内容为空,即对象的内容是空白的。
空值表示对象的内容无法确定。
2、对象的值不同 null表示对象计算中具有保留的值,用于指示指针不引用有效对象。
空值表示值未知,空值一般表示数据未知、不适用或将在以后添加数据。

#3表间前提,表间操作,查询
*代表所有
一般查询(用方式2)
select 字段s from 表名1 join 表名2
on 一个表.主键字段=另一个表.外键字段
where 条件
/*
select 字段s from 表名1,表名2
where 一个表.主键字段=另一个表.外键字段#连接表
and 条件;
*/
分组查询,排序
select 字段1,avg(字段2) as 别名
from 表名1 inner join 表名2
on 一个表.主键字段=另一个表.外键字段
where 条件
group by 字段1
having 分组后筛选条件#不可引用,mysql不报错,sqlSever报错
order by 别名;#可引用
子查询
#2.子查询,先内后外,多条记录用in
例子
select studentname from student
where studentno in
(select studentno from result
where subjectno=
(select subjectno from course where subjectname='java')
and studentresult=60);