MySQL学习一
MySQL数据库管理工具Navicat基本使用方法
本文转自:https://www.cnblogs.com/neuedu/p/5876874.html
- select——查询
- insert——插入
- update——更新
- delete——删除
- from——从哪个表
- where——查询条件
- join——表连接
- order by——排序
一、确保mysql安装成功
下图是mysql安装成功,并启动服务的标志:
二、打开navicat软件,将navicat与本地mysql服务连接
- 点击链接:
- 出现如下界面, 按照自己安装mysql中的信息,填好。出现下面的信息,证明连接成功。
三、创建数据库
-
首先打开一个执行sql语句的窗口;
-
执行创建数据库的sql语句,运行。
create database sqltest;
3. 创建数据库的sql执行后,需要刷新,在下图位置,右键,点击refresh。
然后就能看见新建的sqltest数据库了
四、创建表的语句
- 首先打开sqltest数据库执行sql的窗口。
注意:刚才打开执行sql的窗口是执行整个数据库的sql的窗口,现在我们要在sqltest数据库中执行sql语句,那么就要打开sqltest的sql窗口。
- 在上图红箭处Querries右键新建一个query,就打开了执行sql的窗口,然后执行创建表的sql语句:
create table test(
id int not null primary key,
name varchar(50),
age int
);
- 利用软件添加一条数据
五、insert语句
- 打开执行sql语句的窗口,写入sql语句。
六、select语句
- 利用select语句查看表中的数据:
- 下面是带查询条件的sql语句:
select name,age from test where id=1;
这条sql语句的意思是,查询在test表中,id为1的数据,将这条数据的name属性和age属性查询出来。
七、update语句
update test set name='test3' where id=1;
select *from test;
修改test表中,id为1的数据,将name修改为test3,然后我们可以用select语句,查看表中数据是否改变。
八、delete语句
delete from test where id=2;
select *from test;
删除test表中,id=2的数据。
九、表连接查询
-
建立两张表,分别为学生表student和 教师teacher
-
表,表结构和其中的数据如图:
student表:
id:主键(一条数据的标识,每条数据的主键肯定不同)
name:学生姓名
teacher_id:外键 该学生所对应的教师的idteacher表:
id:主键(一条数据的标识,每条数据的主键肯定不同)
name:教师姓名
create table student (
id int not null primary key,
name varchar(50),
teacher_id int
);
create table teacher (
id int not null primary key,
name varchar(50)
);
- 同时输入多条数据:
insert into student values
(1,'zhangsan',1),
(2,'lisi',1),
(3,'wangwu',2);
insert into teacher values
(1,'teacher1'),
(2,'teacher2');
- 现在我想知道学生zhangsan的老师的名字是什么?
思路:在student表中,能够看出,学生zhangsan所对应的教师的id,也就是teacher_id是1,在teacher表中,id为1的教师的那么是teacher1,那么就能得出学生zhangsan的老师的名字是teacher1,
那么用sql怎么实现呢,这就是表的连接:
select name from teacher where
id=(select teacher_id from student where
name='zhangsan');
上面图中的sql语句就是一个最简单的表连接,能够看出就是最基本的select、from、where组合,上图中的sql首先去看括号中的语句,也就是**select teacher_id from student where name=‘zhangsan’ **这条语句能够查询出名字为zhangsan的学生的teacher_id ,我们能在表中找出值为1,那么剩余的也就是括号外的sql语句就变成了 select name from teacher where id=1; 这样,教师的名字就得到了。
十、其他重要的sql语句
select count(*) from test 查询test表中共有多少条数据
select count(*) from test where age=21 查询test表中age为21的数据一共有多少条,
select count(*) from test where age>21 查询test表中age大于21的数据一共有多少条,数据库中的int类型支持大于小于等比较。
select count(*) from test where age>21 and age<30 查询test表中age大于21并且小于30的数据一共有多少条。
select * from test order by id desc 按id降序排序。
还有一种查询是查询从第几条到第几条,也就是分页查询, 不同的数据库sql语句不同,mysql数据库用的是limit语句,oracle用rownum语句……
还有很多查询方式,但都是select、from、where……这些基础的组合……
在数据库中自己会有一些运算的函数,比如求和的add函数等,还能自定义函数,函数就比较难了。