前面已经介绍过数据库原理、mysql5.7安装、数据库设计/开发,而当数据库安装完成以后,与程序开发用c、c++、java、python等变成语言不一样,数据库须要使用专门的SQL语言进行操做。java
对数据库的操做,基本上就是增、删、改、查、链接5大类操做,能够采用以前安装好的mysql5.7进行实际操做测试。python
一、登陆与建立数据库mysql
#登陆进入数据库c++
mysql -u root -p
#查看已有的数据库
sql
show databases;
#建立名为testdatabase的数据库,使用utf8编码
数据库
create database testdatabase default character set utf8 collate utf8_bin;
#使用testdatabase数据库
bash
use testdatbase
二、增:数据库设计
2.1建立数据库表ide
create table <tablename> (column_name column_type);
#实例:
测试
create table test ( test_id int auto_increment, test_username varchar(20) not null, test_number varchar(10) not null, primary key (test_id) );
2.2插入数据库
insert into test (test_id,test_username,test_number) values (1,'zhangsan','3');
三、删除
3.1删除行
delete from test where test_id = 4;
3.2删除表
3.3删除数据库
四、查
4.1精确匹配
select test_username,test_number from test where test_id = 4;
4.2模糊匹配
select test_username,test_number from test where test_username like '%test2';
五、改
5.1更新数据
update <table_name> set field1=new_value1,field2=new_value2
#实例:
update test set test_username='test0',test_number='1' where test_id=1;
5.2插入列(新字段)
alter table TABLE_NAME add column NEW_COLUMN_NAME varchar(20) not null;
六、链接
上述增删查改命令都是很好入门的,由于上面的命令基本上都是单表操做就能够了。可是对于有关联关系的表格,如何进行跨表查询呢,这个就须要使用链接(UNION)了。
咱们能够拿上一篇(【实战演练】数据库基本知识与原理系列02-数据库设计与开发的范式http://www.javashuo.com/article/p-neeamuqj-ce.html)的实例来进行链接查询试试。
假设如今我想查询,选修了ID号为0001的课程的学生学号、姓名、年龄、成绩、授课老师名、职称、上课时间、上课地点。那么,明显单表查询是不行的,由于不一样的字段分别都散落在学生表、成绩表、课程表、老师表里面了。须要写SQL语句链接这4张表,才能查询到须要的结果。
那么须要这样思考:
1)首先,最终筛选的条件,是ID号为0001的课程,因此就是课程表里面的cno = '2019030001';写成SQL就是where cno = '2019030001';
2)找出需求字段,在每一个表里面的字段名
学号:student.sno
姓名:student.sname
年龄:student.sage
成绩:score.cscore
授课老师名:teacher.tname
职称:teacher.ttitle
上课时间:course.ctime
上课地点:course.cplace
3)清楚每张表格之间经过那个那个外键进行链接的,而后写成表格A.主键=B.外键将表格进行链接便可,例如:成绩表里面,外键引用了学生表学号sno,课程表的cno。
所以链接就是join student.sno = score.sno,而后再join score.sno = course.cno,就能够经过中间表,将学生表与课程表链接起来了。
4)另外,若是每张表写全名,很复杂,所以能够自定义别名,例如student a,那么后面student.sno只须要写成a.sno就能够了。
最终造成语句:
select a.sno,a.sname,a.sage,b.cscore,c.ctime,c.cplace,d.tname,d.ttitle from student a join score b on a.sno = b.sno_id join course c on b.cno_id = c.cno join teacher d on c.tno_id = d.tno where c.cno = '2019030001';
最终就能够实现,查询“选修了ID号为0001的课程的学生学号、姓名、年龄、成绩、授课老师名、职称、上课时间、上课地点”这样的跨表复杂查询了。