MySql第一天
MySql第一天
从命令行连接数据库
mysql -u root -p
使用 mysqladmin 创建数据库
mysqladmin -u root -p create RUNOOB
创建数据库
create database tunny;
删除数据库
drop database <datebase name>;
选择数据库
use <database name>;
创建表
create table school(
school_id int(10) not null auto_increment primary key,
school_name varchar(20)
);
CREATE TABLE IF NOT EXISTS `runoob_tbl`(
`runoob_id` INT UNSIGNED AUTO_INCREMENT,
`runoob_title` VARCHAR(100) NOT NULL,
`runoob_author` VARCHAR(40) NOT NULL,
`submission_date` DATE,
PRIMARY KEY ( `runoob_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
删除表
drop table <table name>;
查看数据库中表
show tables;
查看表结构
desc <table name>;
DML操作
插入数据
-- 一次性列出全部字段的值
INSERT INTO student VALUES('Chenqi','M', 29);
INSERT INTO student VALUES('Bush','M', 60),('Obama', 'M', 45);
-- 只对部分字段赋值
INSERT INTO student(name, sex) VALUES ('Abby', 'F'),('Joseph', 'M');
-- 使用SET子句
INSERT INTO student SET name='Stein', sex='M';
删除数据
delect from school; -- 删除所有数据
delect from school where school_id = 3; -- 删除school_id为3的数据
修改数据
update t_user SET nickname = '张小二' where nickname = '王小二';
查询数据
select * from school;
MYSQL数据库-约束
修改表的结构
alert
外键约束
-- 主表teacher
CREATE TABLE teacher (
tid int NOT NULL AUTO_INCREMENT,
tname varchar(20) DEFAULT NULL,
salary int DEFAULT NULL,
PRIMARY KEY (`tid`)
);
-- 从表student
create table student (
sid int auto_increment primary key,
sname varchar(20),
ssex varchar(2) DEFAULT '女',
tid int,
FOREIGN KEY(tid) REFERENCES teacher(tid)
);
例子
create table department ( -- 系部表
did char(6) PRIMARY key,
dname char(30) not null,
ddirector char(8)
);
create table major ( -- 专业表
mid char(4) primary key,
mname char(20) not null,
did char(6),
foreign key(did) REFERENCES department(did)
);
create table class (
cid char(9) primary key,
cname char(20),
mid char(6),
did char(6),
remarks char(50),
foreign key(mid) references major(mid),
foreign key(did) references department(did)
);
create table student ( -- 学生表
sid char(12) primary key,
sname char(80),
ssex char(2),
birthdate datetime,
enrollmenttime datetime,
did char(6),
mid char(4),
cid char(12),
foreign key(did) references department(did),
foreign key(mid) references major(mid),
foreign key(cid) references class(cid)
);
查询
连接查询
-- 自然内连接
select * from s_user natural join s_orderform;
-- 自然左外连接
select * from s_user natural left join s_orderform;
-- 自然右外连接
select * from s_user natural right join s_orderform;
mysql 时间比较
SELECT * FROM `contest` WHERE DATE(`cjsfbtime`) BETWEEN '2018-08-20' AND '2018-09-31'
版权声明:本博客(网站地址)刊载的所有内容,包括文字、图片、音频、视频、软件、程序、等版权归作者所有,咨询新浪微博:@Tunny张文鹏