赞
踩
服务端:主要存储数据,并接收用户发过来的SQL语句,并执行结果返回给客户端
客户端:下发用户要执行的sql语句,并显示服务器返回的执行结果
查看所有的数据库 | show database; |
使用数据库 | use 数据库名; |
查看当前使用的数据库 | select database(); |
创建数据库 | create database 数据库名 charset=utf8; |
删除数据库 | drop database 数据库名; |
查看数据库所有的表 | show tables; |
查看数据库表的结构 | desc 表名;(desc =describe) |
查看数据表的创建语句 | show create table 表名; |
语法:
create table表名(
字段名1 类型 约束,
字段名2 类型 约束
... ... ...
)
例子:
创建一个学生表,字段要求:姓名(长度为10),年龄,身高(保留2位小数)
- CREATE table students(
- id int UNSIGNED PRIMARY KEY auto_increment,
- name VARCHAR(20),
- height decimal(5,2)
- )
drop table 表名 (该命令将永久性删除表和其所有数据)
drop table if exists students (删除表之前检查表是否存在。如果表存在,则表会被删除;如果表不存在,则不会引发错误)
insert into 表名 values(...)
例子:
insert into students values(0,'jingbeng',12.66);
//主键自增长可以用0或者NULL代替
另一种写法:
insert into students(name) values('nnn')
insert into students(name) value ('jingbeng1');
insert into students(name) value ('jingbeng3');
insert into students values(0,'jingbeng2',23,167.56)
例: insert into students values(0,'亚瑟3',23,167.56),(0,'亚瑟4',23,167.56)
例: insert into students(name) value ('老夫子5'),('老夫子6')
例子:select * from students;
例子:select name,sex,age from students;
例子:select s.name,s.age from students as s;
例子:select name as n,age as a from students;
例: select * from students where id=1;
说明: where支持多种运算符进行条件处理
比较运算
范围查询
空判断
例1:查询小乔的年龄
select age from students where name='小乔’
例2:查询20岁以下的学生
select * from students where age<20
例3:查询家乡不在北京的学生
select * from students where hometown!='北京'
例1:查询年龄小于20的女同学
select * from students where age<20 and sex='女'
例2:查询女学生或'1班'的学生
select * from students where sex='女' or class='1班
例3:查询非天津的学生
select * from students where not hometown='天津'
% :匹配任意多个字符
- : 匹配一个任意字符
例1:查询姓孙的学生
select * from students where name like '孙%'
例2:查询姓孙且名字是一个字的学生
select * from students where name like '孙_'
例3:查询姓名以‘乔’结尾的学生
select * from students where name like '%乔'
例4:查询姓名中包含‘白’的学生
select * from students where name like '%白%'
例:查询家乡是北京或上海或广东的学生
select * from students where hometown in('北京','上海','广东')
例:查询年龄为18至20的学生
select * from students where age between 18 and 20
注意:Mysql中空表示null,与 ‘’ (空)是不一样的。
判断为空: is null
例:查询没有填写身份证的学生
select * from students where card is null
判断非空: is not null
例:查询填写了身份证的学生
select * from students where card is not null
使用聚合函数是为了方便进行数据进行统计
聚合函数不能在where中使用:
count():查询总记录数
max(字段名):查询最大值
min(字段名):查询最小值
sum(字段名):求和
avg(字段名):求平均数
where 是对 from 后面指定的表进行数据筛选,属于对原始数据的筛选。
having 是对 group by 的结果进行筛选。
having 后面的条件中可以用聚合函数,where后面不可以。
语法:select * from 表名 limit start count
start表示开始位置,索引默认从0开始
count表示从start位置开始获取count条数据
例子:获取学生表的第2-4行的信息
select * from students limit 1,3;
分页查询:select * from students limit (n-1)*m,m
说明:n表示显示第几页的数据;m表示每页显示多少条数据
语法:
select * from 表1 inner join 表2 on 表1.列=表2.列;
select * from 表1,表2 where 表1.列=表2,列;
定义:(右连接反之)
语法:select * from 表1 left join 表2 on 表1.列=表2.列
语法:delete from 表名 where 条件;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。