查看版本
示例:select version();
查看当前时间:
示例:select now();
二. 数据库操作
1 创建数据库
create database name charset='utf8';
2 删除数据库
drop database name;
3 切换数据库
use name;
4 查看当前数据库
select database();
三. 表操作
1 查看表
show tables;
2 创建表
create table name(列及类型)
create table t1(id int auto_increment primary key, name varchar(20) not null);
id 名字
auto_increment primary key 主键递升
not null 不为空
3 删除表
drop table name;
4 查看表结构
desc name
5 查看建表语句
show create table name;
6 重命名表
rename table old to new
7 修改表
alter table name add/change/drop 列名 类型;
四. 数据操作
1 增
全列插入
insert into name value(0,);向主键写0,主键会自动变化
缺省插入
insert into name(列1,列2) value(0,);向主键写0,主键会自动变化
同时插入多条数据
insert into name values(),(),(),()
2 删
删除表名
delete from name where id=1;
3 改
update name set 列1=值1, 列2=值2,。。。 where
4 查
select * from table_name
五. 查
1 基本语法
select * from table_name;
select name as a from table_name;
2 消除重复行
select distinct name from student;
3 条件查询
比较运行运算符 >,<,=,!=
逻辑运算符 and,or,not
模糊查询 like %任意多个,_任意一个字符
select * from test where name like "t%"
范围查询
in 在一个非连续的范围内
select id, name from test where id in (3,5,7);
between and 在一个连续的范围内
select id, name from test where id between 3 and 10;
空判断 null与""不一样,判断空is null, is not null
优先级 and>or
4 聚合
count(*) 计算总行数,括号民中可为*或列名
select id, name from test where id between 3 and 10;
+----------+
| count(*) |
+----------+
| 19 |
+----------+
max() select max(id) from test where id between 3 and 10;
min()
sum()
abs()
5 分组
select c1,c2... from table_name group by 列1,列2,...
select gender,count(*) from test group by gender;
+--------+----------+
| gender | count(*) |
+--------+----------+
| | 6 |
| 1 | 13 |
+--------+----------+
分组后的数据筛选
select gender, count(*) from test group by gender having gender;
mysql> select gender, count(*) from test group by gender having gender;
+--------+----------+
| gender | count(*) |
+--------+----------+
| | 13 |
+--------+----------+
1 row in set (0.00 sec)
mysql> select gender, count(*) from test group by gender having gender=0;
+--------+----------+
| gender | count(*) |
+--------+----------+
| | 6 |
+--------+----------+
1 row in set (0.00 sec)
6 排序
select * from test order by age asc;
select * from test order by age desc;
select * from test order by age desc, id asc;
7 分页
select * from student limit 0,3; 前三行 start,count
select * from student limit 3,3; 前三行
关联
create table class(id int auto_increment primary key, name varchar(20) not null,stuNum int not null);
create table students(id int auto_increment primary key, name varchar(20) not null, gender bit default 1, classid int not null, foreign key(classid) references class(id));
关联查询
select students.name, class.name from class inner join students on class.id=students.classid;
select students.name, class.name from class inner join students on class.id=students.classid where class.name='333';
分类
表A inner join 表B 表A与表B匹配的行会出现在结果集中
表A left join 表B 表A与表B匹配的行会出现在结果集中,外加表A中独有的数据,未对应的数据使用NULL填充