当前位置: 萬仟网 > IT编程>数据库>Mysql > mysql基础(附具体操作代码)

mysql基础(附具体操作代码)

2020年01月13日  | 萬仟网IT编程  | 我要评论
# 注释内容
-- 注释内容
-- 创建数据库 king
create database king;
-- 查看当前服务器下有哪些数据库
show databases;
show schemas;
-- 查看king数据库的详细信息
show create database king;

-- 创建数据库queen 并且指定编码方式为gbk
create database if not exists queen default character set 'gbk';
-- 查看当前服务器下全部的数据库
show databases;
-- 查看queen指定数据库的详细信息
show create database queen;
-- 将queen的数据库的编码方式改为utf8
alter database queen default character set 'utf8';
-- 打开queen的数据库
use queen;
-- 得到当前打开的数据库
select database();
select schema();
-- 删除king数据库
drop database if exists king;
drop database if exists queen;
-- 创建测试用数据库 test
create database if not exists test default character set 'utf8';

-- 打开test

use test;

-- 用户表 test_user

create table if not exists test_user(
id int,
username varchar(20),
password char(32),
email varchar(50),
age tinyint,
card char(18),
tel char(11),
salary float(8,2),
married tinyint(1),
addr varchar(100),
sex enum('男','女','保密')
)engine=innodb charset=utf8;

-- 查看test_user表的表结构
desc test_user;

describe test_user;

show columns from test_user;

-- 删除test_user表

drop table if exists test_user;

-- 查看当前数据库下的数据表

-- 查看test_user表的详细信息

-- 通过三种方式查看指定数据表的表结构

-- 最后删除test_user数据表

数据库增加数据与查询数据

-- 用户表 test_user

create table if not exists test_user(
id int,
username varchar(20),
password char(32),
email varchar(50),
age tinyint,
card char(18),
tel char(11),
salary float(8,2),
married tinyint(1),
addr varchar(100),
sex enum('男','女','保密')
)engine=innodb charset=utf8;

-- insert [into] tbl_name(id,username,...) values(1,'king',...);

-- 向test_user表插入一条记录
insert test_user(id,username,password,email,age,card,tel,salary,married,addr,sex)
values(1,'king','king','965794175@qq.com',24,'xxxxxxxxxxxxxxxxxx','132xxxxxxxx',88888.68,0,'宁波','男');

-- 查询表中所有记录 select * from tbl_name;

select * from test_user;

insert test_user(id,username,password,email,age,card,tel,salary,married,addr,sex)

values(-5,'king','123456','965794175@qq.com',190,'xxxxxxxxxxxxxxxxxx','132xxxxxxxx',2345.68,1,'宁波','女');

数据类型测试-测试整型+无符号+零填充

-- 测试整型
create table test_int(
    a tinyint,
    b smallint,
    c mediumint,
    d int,
    e bigint
);
insert test_int(a) values(-128);
-- 如果超出数据的范围,会产生截断现象
insert test_int(a) values(-129);
insert test_int(a) values(1270);

-- 测试无符号

create table test_unsigned(
a tinyint,
b tinyint unsigned
);

insert test_unsigned(a,b) values(-12,-12);
insert test_unsigned(a,b) values(0,0);
insert test_unsigned(a,b) values(0,256);

-- 测试零填充 zerofill
create table test_int1(
    a tinyint zerofill,
    b smallint zerofill,
    c mediumint zerofill,
    d int zerofill,
    e bigint zerofill
);

insert test_int1(a,b,c,d,e) values(1,1,1,1,1);

create table test_int2(
    a tinyint(2),
    b smallint(2)
);
insert test_int2(a,b) values(123,45678);

数据类型测试-测试浮点型

-- 测试浮点型
create table test_float(
a float(6,2),
b double(6,2),
c decimal(6,2)
);

insert test_float(a,b,c) values(4.143,4.146,4.149);

create table test_float1(
a float,
b double,
c decimal
);
insert test_float1(a,b,c) values(4.143,4.146,4.649);
insert test_float(a,b,c) values(1234567.89,2345678.9,567890.89);

数据类型测试-测试char和varchar+text+enum+set

-- 测试char 和 varchar
create table test_str(
    a char(5),
    b varchar(5)
);
insert test_str(a,b) values('','');
insert test_str(a,b) values('a','a');
insert test_str(a,b) values('ab','ab');
insert test_str(a,b) values('abc','abc');
insert test_str(a,b) values('abcd','abcd');
insert test_str(a,b) values('abcde','abcde');
insert test_str(a,b) values('abcdef','abcdef');

insert test_str(a,b) values(' 123 ',' 123 ');

select concat('*',a,'*'),concat('*',b,'*') from test_str;

-- 测试text不能有默认值
create table test_str1(
 content text default 'this is a test'
);


-- 测试enum
create table test_enum1(
sex enum('男','女 ','保密 ')
);
insert test_enum(sex) values('男');
insert test_enum(sex) values('男1');
insert test_enum(sex) values(null);
insert test_enum(sex) values(1);
insert test_enum(sex) values(3);
insert test_enum(sex) values(5);

-- 测试set
create table test_set(
    a set('a','b','c','d','e','f')
);

insert test_set(a) values('a');
insert test_set(a) values('c');
insert test_set(a) values('c,d,e');
insert test_set(a) values('c,f,a');
insert test_set(a) values('c,f,a,h');
insert test_set(a) values(2);

数据类型测试-测试时间类型

-- hh:mm:ss [d hh:mm:ss] d表示天数 0~34
-- 测试time类型
create table test_time(
a time
);
insert test_time(a) values('12:23:45');
insert test_time(a) values('2 12:23:45');
insert test_time(a) values('22:22');
insert test_time(a) values('22');
insert test_time(a) values('2 22');
-- hhmmss
insert test_time(a) values('121212');
insert test_time(a) values('0');
insert test_time(a) values(0);
insert test_time(a) values('787878');

insert test_time(a) values(now());
insert test_time(a) values(current_time);

-- 测试date类型 yyyy-mm-dd yyyymmdd
create table test_date(
    a date
);
insert test_date(a) values('2017-03-04');
insert test_date(a) values('2017-2-13');
insert test_date(a) values('4007-03-23');
insert test_date(a) values('40071212');
insert test_date(a) values('4007@12@12');
insert test_date(a) values('4008#13#13');
insert test_date(a) values('4009.8.14');


-- yy-mm-dd yymmdd
-- 70~99 转换成1970~1999 00~69 2000~2069
insert test_date(a) values('780902');
insert test_date(a) values('650902');
insert test_date(a) values('880902');
insert test_date(a) values(now());
insert test_date(a) values(current_date);

-- 测试datetime

create table test_datetime(
a datetime
);
insert test_datetime(a) values('1004-09-12 13:24:56');
insert test_datetime(a) values('720305121212');
insert test_datetime(a) values(now());
insert test_datetime(a) values(datetime);

-- 测试timestamp
create table test_timestamp(
    a timestamp
);
insert test_timestamp(a) values('1978-10-23 12:12:12');

-- 插入current_timestamp
insert test_timestamp values(current_timestamp);

-- 插入null
insert test_timestamp values(null);

-- 什么也不写 得到当前系统日期和时间
insert test_timestamp values();


-- 测试year

create table test_year(
    a year
);

insert test_year(a) values(1901);

-- 00~69 2000~2069 70~99 1970~1999
-- 0 插入的结果是0000
-- '0' 插入的结果是2000

数据类型测试-测试主键+复合主键+自增

-- 测试主键
create table test_primary_key(
    id int unsigned primary key,
    username varchar(20)
);
insert test_primary_key(id,username) values(1,'king');
insert test_primary_key(id,username) values(1,'king123');
insert test_primary_key(username) values('queen');

create table test_primary_key1(
    id int unsigned key,
    username varchar(20)
);

create table test_primary_key2(
    id int unsigned,
    username varchar(20),
    primary key(id)
);

-- create table test_primary_key3(
--     id int unsigned primary key,
--     courseid int unsigned primary key,
--     username varchar(20),
--     email varchar(50)
-- );

-- 复合主键
create table test_primary_key3(
    id int unsigned,
    courseid varchar(20),
    username varchar(20),
    email varchar(50),
    primary key(id,courseid)
);
-- 1-a
insert test_primary_key3(id,courseid,username,email)
values(1,'a','king','965794175@qq.com');

insert test_primary_key3(id,courseid,username,email)
values(1,'b','king','965794175@qq.com');

insert test_primary_key3(id,courseid,username,email)
values(2,'a','king','965794175@qq.com');

insert test_primary_key3(id,courseid,username,email)
values(1,'a','1king','965794175@qq.com');

-- 测试auto_increment

create table test_auto_increment(
id int unsigned key auto_increment,
username varchar(20)
);

insert test_auto_increment(username) values('a');
insert test_auto_increment(username) values('b');
insert test_auto_increment(username) values('c');

insert test_auto_increment(id,username) values(null,'e');
insert test_auto_increment(id,username) values(default,'f');
insert test_auto_increment(id,username) values(15,'g');

数据类型测试-测试非空+默认值+唯一键

-- 测试非空
create table test_not_null(
a varchar(20),
b varchar(20) not null
);

insert test_not_null(a,b) values('','');
insert test_not_null(a,b) values(null,null);
insert test_not_null(a,b) values(null,'abc');
insert test_not_null(a) values('test');

-- 测试默认值
create table test_default(
id int unsigned auto_increment key,
username varchar(20) not null,
age tinyint unsigned default 18,
email varchar(50) not null default '965794175@qq.com'
);
insert test_default(username) values('a');
insert test_default(username,age,email) values('b',30,'965794175@qq.com');
insert test_default(username,age,email) values('c',null,'965794175@qq.com');
insert test_default(username,age,email) values('d',null,null);
insert test_default(username,age,email) values('d',null,default);

create table test_default1(
id int unsigned auto_increment key,
sex enum('a','b','c') not null default 'a'
);

-- 测试unique key
create table test_unique(
id int unsigned auto_increment key,
username varchar(20) not null unique key,
email varchar(50) unique,
card char(18) unique
);

insert test_unique(username,email,card) values('a','a@qq.com','1');
insert test_unique(username,email,card) values('a','1a@qq.com','12');
insert test_unique(username,email,card) values('b',null,null);
insert test_unique(username,email,card) values('c',null,null);

数据类型测试-测试布尔类型

-- 用户表test_user
create table if not exists `test_user`(
`id` int unsigned auto_increment key comment '用户编号',
`username` varchar(20) not null unique comment '用户名',
`password` char(32) not null comment '密码',
`email` varchar(50) not null unique comment '邮箱',
`age` tinyint unsigned not null default 18 comment '年龄',
`sex` enum('男','女','保密') not null default '保密' comment '性别',
`tel` char(11) not null unique comment '电话',
`addr` varchar(50) not null default '北京' comment '地址',
`card` char(18) not null unique comment '身份证号',
`married` tinyint(1) not null default 0 comment '0代表未结婚,1代表已结婚',
`salary` float(8,2) not null default 0 comment '薪水'
)engine=innodb default charset=utf8;

-- 测试布尔类型
create table test_bool(
id int,
married bool
);
create table test_bool1(
id int,
married boolean
);

对数据表字段的增删改

-- 测试添加和删除字段
create table if not exists user1(
    id int unsigned auto_increment key
);

-- 添加用户名字段 username varchar(20)
alter table user1
add username varchar(20);

-- 添加密码字段 password char(32) not null
alter table user1
add password char(32) not null;

-- 添加邮箱字段 email varchar(50) not null unique 加到username之后
alter table user1
add email varchar(50) not null unique after username;

-- 添加测试字段 test tinyint(1) not null default 0; 加到首位
alter table user1
add test tinyint(1) not null default 0 first;

-- 删除test字段
alter table user1
drop test;


-- 添加age、addr字段,删除email字段
alter table user1
add age tinyint unsigned not null default 18,
add addr varchar(100) not null default '北京',
drop email;

-- 创建数据表 id / proname
-- 添加price float(8,2) unsigned not null default 0
-- 添加num int unsigned not null default 100
-- 添加测试字段test varchar(50) not null 加到首位
-- 添加测试字段test1 char(23) not null 添加到price之后
-- 删除test字段

-- 选中一次数据表完成多次操作,添加一个desc text, 添加issale 布尔类型 0下架 1代表在卖
-- 删除test1字段

-- 测试添加删除默认值操作
create table user2(
id int unsigned auto_increment key,
username varchar(20) not null,
age tinyint unsigned not null default 18,
email varchar(50) not null
);
-- 给email字段添加默认值 test@qq.com
alter table user2
alter email set default 'test@qq.com';

-- 删除age字段的默认值
alter table user2
alter age drop default;

-- 添加地址字段
-- 给地址字段添加默认值为北京
-- 删除商品数量的默认值


-- 测试修改字段类型和字段属性、字段名称
create table user3(
id int unsigned auto_increment key,
username varchar(5) not null unique,
password char(32) not null,
email varchar(10) not null
);

-- 将用户名字段的类型改为20
alter table user3
modify username varchar(20) not null;

-- 将密码的长度改为40
alter table user3
modify password char(40) not null;

-- 将email字段改为varchar(50) not null first

alter table user3
modify email varchar(50) not null first;

-- 将username 名称改为user
alter table user3
change username user varchar(20) not null;

-- 将password 名称改为pwd
alter table user3
change password pwd char(40) not null;

-- 将email改成useremail 类型改成varchar(100) default 'test@qq.com'

alter table user3
change email useremail varchar(100) default 'test@qq.com';


-- 测试添加和删除主键
create table user4(
id int unsigned,
username varchar(20) not null
);

-- 添加主键
alter table user4
add primary key(id);

-- 删除主键
alter table user4
drop primary key;

create table user5(
id int unsigned auto_increment key,
username varchar(20) not null
);

-- 将id的auto_increment去掉
alter table user5
modify id int unsigned;

-- 测试添加和删除唯一
create table user6(
id int unsigned auto_increment key,
username varchar(20) not null unique,
password char(32) not null,
email varchar(50) not null unique
);

-- 删除唯一索引 username 和email
alter table user6
drop index username;


alter table user6
drop index email;

-- 添加唯一索引
alter table user6
add unique key(username);

alter table user6
add unique index uni_email(email);

-- 将user6改为user666
alter table user6
rename to user666;


alter table user666
rename as user6;

alter table user6
rename user666;

rename table user666 to user6;

存储引擎

-- 测试memory存储引擎
create table m1(
a varchar(100)
)engine=memory;

-- 测试csv存储引擎
create table c1(
a varchar(20) not null,
b varchar(20) not null
)engine=csv;
insert c1(a,b) values('aaa','bbb');
insert c1(a,b) values('ccc','ddd');

-- 测试archive存储引擎
create table a1 as select * from information_schema.columns;

insert into a1 select * from a1;

-- 11026432 57177

create table a2 engine=archive as select * from a1;

-- 742354 55392

-- 测试myisam存储引擎
create table test_myisam(
    a int unsigned,
    b varchar(20),
    c char(32)
)engine=myisam;


create table myisam_1(
a char(30),
id int
)engine=myisam;

create table myisam_2(
a varchar(30),
id int
)engine=myisam;

create table myisam_3(
a varchar(30),
id int
)engine=myisam row_format=fixed;


create table test_innodb(
 id int unsigned auto_increment key,
 username varchar(20) not null     
);

添加数据

-- 测试添加记录
create database if not exists king default character set 'utf8';
use king;
create table if not exists user(
    id int unsigned auto_increment key comment '编号',
    username varchar(20) not null unique comment '用户名',
    age tinyint unsigned default 18 comment '年龄',
    email varchar(50) not null default 'test@qq.com' comment '邮箱'
)engine=innodb charset=utf8;

-- 不指定字段名称
insert user value(1,'king',24,'965794175@qq.com');
insert user values(null,'queen',25,'queen@qq.com');
insert user values(default,'lily',26,'lily@qq.com');

-- 列出指定字段的形式
insert user(username,email) values('rose','rose@qq.com');
insert user(age,email,id,username) values(34,'test@qq.com',5,'test');

-- 一次插入3条记录
insert user values(null,'a',default,default),
(null,'b',56,'b@qq.com'),
(null,'c',14,'c@qq.com');

-- insert ...set 的形式
insert user set username='d',age=45,email='d@qq.com';

-- insert select
insert user(username) select a from test;

修改删除数据

-- 测试更新语句
-- 修改第一个用户的信息 id=1
update user set age=29 where id=1;

-- 修改id=3的用户,username age email
update user set age=47,email='lilys@qq.com',username='lilys' where id=3;

-- 所有用户年龄+10
update user set age=age+10;

-- 将id<=5的用户年龄改为-20,将邮箱改为默认值
update user set age=age-20,email=default where id<=5;

-- 测试删除语句
-- 删除用户名为king
delete from user where username='king';

-- 删除年龄为24的用户
delete from user where age=24;

-- 删除表中所有记录
delete from user;

insert user values(null,'queen',25,'queen@qq.com');
insert user values(default,'lily',26,'lily@qq.com');

查询操作

-- 测试查询操作
create table user1(
id int unsigned auto_increment key,
username varchar(20) not null unique comment '编号',
age tinyint unsigned not null default 18  comment '年龄',
sex enum('男','女','保密') not null default '保密' comment '性别',
addr varchar(20) not null default '宁波',
married tinyint(1) not null default 0 comment '0代表未结婚,1代表已婚',
salary float(8,2) not null default 0 comment '薪水'
)engine=innodb charset=utf8;
insert user1 values(1,'king',23,'男','宁波',1,50000);
insert user1(username,age,sex,addr,married,salary) values('queen',27,'女','上海',0,25000);
insert user1 set username='test',age=31,sex='女',addr='宁波',salary=40000;
insert user1 values(null,'张三',38,'男','上海',0,15000),
(null,'张三风',38,'男','上海',0,15000),
(null,'张子怡',39,'女','宁波',1,85000),
(null,'汪峰',42,'男','深圳',1,95000),
(null,'刘德华',58,'男','广州',0,115000),
(null,'吴亦凡',28,'男','宁波',0,75000),
(null,'奶茶妹',18,'女','宁波',1,65000),
(null,'刘嘉玲',36,'女','广州',0,15000);

-- 查询表中所有记录
select * from user1;

-- username,addr,age
select username,addr,age from user1;

-- 查询king数据库下user1表中的所有记录
select * from king.user1;

-- 查询user1表中的id 编号 username 用户名 sex 性别
select id as '编号',username as '用户名', sex as '性别'
from user1;

select id age,age id,username from user1;

-- 给表起别名
select id,username from user1 as u;

-- 测试表名.字段名
select user1.id,user1.username,user1.age from user1 ;

select u.id,u.username,u.addr,u.sex from user1 as u;

-- 测试where 条件的比较运算符
-- 查询id,username,age id=5的用户
select id,username,age from user1
where id=5;

select id,username,age from user1
where id=50;

-- 添加desc字段 varchar(100)
alter table user1
add userdesc varchar(100);

-- 更新id<=9的用户 userdesc='this is a test'

update user1 set userdesc='this is a test'
where id<=9;

-- 查询用户userdesc 为null的用户
select id,username,age,userdesc from user1
where userdesc=null;

-- 检测null值
select id,username,age,userdesc from user1
where userdesc<=>null;

-- is [not] null检测null值
select id,username,age,userdesc from user1
where userdesc is null;

-- 测试范围between and
-- 查询年龄在18~30之间的用户
select id,username,age,sex from user1
where age between 18 and 30;

-- 查询薪水在10000~50000之间的用户
select id,username,age,salary from user1
where salary between 10000 and 50000;

select id,username,age,salary from user1
where salary not between 10000 and 50000;

-- 测试指定集合 in

-- 查询编号为1,3,5,7,9
select id,username,age from user1
where id in(1,3,5,7,9,29,45,78);

select id,username,age from user1
where username in('king','queen','lily','rose');

-- 测试逻辑运算符
-- 查询性别为男并且年龄>=20的用户
select id,username,age,sex from user1
where sex='男' and age>=20;

-- id>=5 && age<=30
select id,username,age,sex from user1
where id>=5 and age<=30;

select id,username,age,sex from user1
where id>=5 and age<=30 and sex='男';

-- 要求sex='女' 并且 addr='宁波'
select id,username,age,sex,addr from user1
where sex='女' and addr='宁波';

-- 查询薪水范围在60000~10000并且性别为男 addr='宁波'
select id,username,age,sex,salary,addr from user1
where salary between 60000 and 100000 and sex='男' and addr='宁波';

-- 查询id=1 或者 用户名为queen

select id,username,age from user1
where id=1 or username='queen';

-- 测试模糊查询
select id,username,age from user1
where username='king';

select id,username,age from user1
where username like 'king';

-- 要求用户名中包含三
select id,username,age,sex from user1
where username like '%三%';

-- 用户名中包含n
select id,username,age from user1
where username like '%in%';

-- 要求查询出姓张的用户
select id,username,age from user1
where username like '张%';

-- 查询以风结尾的用户
select id,username,age from user1
where username like '%风';


-- 用户名长度为三位的用户
select id,username,age,sex from user1
where username like '___';

select id,username,age,sex from user1
where username like '张_';

select id,username,age,sex from user1
where username like '张_%';

-- 测试分组
-- 按照性别分组sex
select id,username,age,sex from user1
group by sex;

-- 按照addr分组
select username,age,sex,addr from user1
group by addr;

-- 按照性别分组,查询组中的用户名有哪些
select group_concat(username),age,sex,addr from user1
group by sex;

select group_concat(username),age,sex,group_concat(addr) from user1
group by sex;

-- 测试count()
select count(*) from user1;

select count(id) from user1;

-- 按照sex分组,得到用户名详情,并且分别组中的总人数
select sex,group_concat(username) as usersdetail,count(*) as totalusers from user1
group by sex;

-- 按照addr分组,得到用户名的详情,总人数,得到组中年龄的总和,年龄的最大值、最小值、平均值和
select addr,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(age) as sum_age,
max(age) as max_age,
min(age) as min_age,
avg(age) as avg_age
from user1
group by addr;

-- 按照sex分组,统计组中总人数、用户名详情,得到薪水总和,薪水最大值、最小值、平均值
select sex,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(salary) as sum_salary,
max(salary) as max_salary,
min(salary) as min_salary,
avg(salary) as avg_salary
from user1
group by sex;

select group_concat(username) as usersdetail,
count(*) as totalusers
from user1
group by sex
with rollup;

-- 按照字段的位置来分组
select id,sex,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(salary) as sum_salary,
max(salary) as max_salary,
min(salary) as min_salary,
avg(salary) as avg_salary
from user1
group by 2;

-- 查询age>=30的用户并且按照sex分组
select sex,group_concat(username) as usersdetail,
count(*) as totalusers
from user1
where age>=30
group by sex;

-- 按照addr分组,统计总人数
select addr,
group_concat(username) as usersdetail,
count(*) as totalusers
from user1
group by addr;

-- 对于分组结果进行二次筛选,条件是组中总人数>=3
select addr,
group_concat(username) as usersdetail,
count(*) as totalusers
from user1
group by addr
having count(*)>=3;

select addr,
group_concat(username) as usersdetail,
count(*) as totalusers
from user1
group by addr
having totalusers>=3;

-- 按照addr分组,
select addr,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(salary) as sum_salary,
max(salary) as max_salary,
min(salary) as min_salary,
avg(salary) as avg_salary
from user1
group by addr;

-- 要求平均薪水>=40000
select addr,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(salary) as sum_salary,
max(salary) as max_salary,
min(salary) as min_salary,
avg(salary) as avg_salary
from user1
group by addr
having avg_salary>=40000;

-- 测试排序
-- 按照id降序排列
select id,username,age
from user1
order by id desc;

-- 按照age升序
select id,username,age
from user1
order by age ;

-- 按照多个字段排序
select id,username,age
from user1
order by age asc,id asc;

-- 测试条件+排序
select id,username,age
from user1
where age>=30;

select id,username,age
from user1
where age>=30
order by age desc;

-- 实现随机记录
select id,username,age
from user1
order by rand();

-- 测试limit语句
-- 显示结果集的前5条记录
select id,username,age,sex
from user1
limit 5;

select id,username,age,sex
from user1
limit 0,5;

-- 显示前3条记录
select id,username,age,sex
from user1
limit 0,3;

select id,username,age,sex
from user1
limit 3,3;

-- 更新前3条记录,将age+5
update user1 set age=age+5 limit 3;

-- 按照id降序排列,更新前三条记录,将age-10
update user1 set age=age-10 order by id desc limit 3;

-- 删除前三条记录

delete from user1
limit 3;

delete from user1
order by id desc
limit 3;

-- 测试完整select 语句的形式
select addr,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(age) as sum_age,
max(age) as max_age,
min(age) as min_age,
avg(age) as avg_age
from user1
where id>=2
group by addr;

select addr,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(age) as sum_age,
max(age) as max_age,
min(age) as min_age,
avg(age) as avg_age
from user1
where id>=2
group by addr
having totalusers>=2;


select addr,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(age) as sum_age,
max(age) as max_age,
min(age) as min_age,
avg(age) as avg_age
from user1
where id>=2
group by addr
having totalusers>=2
order by totalusers asc;

select addr,
group_concat(username) as usersdetail,
count(*) as totalusers,
sum(age) as sum_age,
max(age) as max_age,
min(age) as min_age,
avg(age) as avg_age
from user1
where id>=2
group by addr
having totalusers>=2
order by totalusers asc
limit 0,2;

多表查询

create database if not exists test2 default character set 'utf8';
use test2;
create table emp(
id int unsigned auto_increment key,
username varchar(20) not null unique comment '编号',
age tinyint unsigned not null default 18  comment '年龄',
sex enum('男','女','保密') not null default '保密' comment '性别',
addr varchar(20) not null default '宁波',
depid tinyint unsigned not null comment '部门对应的编号'
)engine=innodb charset=utf8;

insert emp(username,age,depid) values('king',24,1),
('queen',25,2),
('test',26,1),
('lily',27,1),
('rose',28,3),
('john',29,3);

insert emp(username,age,depid)  values('测试用户',39,6);

create table dep(
id tinyint unsigned auto_increment key,
depname varchar(50) not null unique,
depdesc varchar(100) not null default ''
)engine=innodb charset=utf8;
insert dep(depname,depdesc) values('php教学部','研发php课件'),
('java教学部','研发java课件'),
('web前端教学部','研发web前端课件'),
('ios教学部','研发ios课件');


-- 查询 emp id username age  部门名称 dep depname

select emp.id,emp.username,emp.age,dep.depname from emp,dep;

select e.id,e.username,e.age,d.depname
from emp as e
inner join dep as d
on e.depid=d.id;

-- 查询emp id username age addr dep id depname depdesc
select e.id,e.username,e.age,e.addr,
d.id,d.depname,d.depdesc
from dep as d
join emp as e
on d.id=e.depid;

-- 测试左外连接
select e.id,e.username,e.age,d.depname,d.depdesc
from emp as e
left outer join dep as d
on e.depid=d.id;

-- 测试右外连接
select e.id,e.username,e.age,d.depname,d.depdesc
from emp as e
right join dep as d
on e.depid=d.id;

实例

-- 创建管理员表
create table user(
id tinyint unsigned auto_increment key,
username varchar(20) not null unique,
email varchar(50) not null default '382771946@qq.com',
proname varchar(10) not null default '北京'
);
insert user(username,proname) values('a','北京'),
('b','哈尔滨'),
('c','上海'),
('d','深圳'),
('e','广州'),
('f','重启');

-- 创建省份表
create table provinces(
id tinyint unsigned auto_increment key,
proname varchar(10) not null unique
);
insert provinces(proname) values('北京'),
('上海'),
('深圳');
--
create table user(
id tinyint unsigned auto_increment key,
username varchar(20) not null unique,
email varchar(50) not null default '965794175@qq.com',
proid tinyint unsigned not null
);
insert user(username,proid) values('a',1);
insert user(username,proid) values('b',1);
insert user(username,proid) values('c',1);
insert user(username,proid) values('d',2);
insert user(username,proid) values('e',3);
insert user(username,proid) values('f',1);
insert user(username,proid) values('g',1);

-- 查询user id ,username provinces proname
select u.id,u.username,p.proname
from user as u
join provinces as p
on u.proid=p.id;

-- 创建省份表
create table provinces(
id tinyint unsigned auto_increment key,
proname varchar(10) not null unique
);

-- 管理员admin id username email proid
create table admin(
id tinyint unsigned auto_increment key,
username varchar(20) not null unique,
email varchar(50) not null default '382771946@qq.com',
proid tinyint unsigned not null
);
insert admin(username,proid) values('king',1);
insert admin(username,proid) values('queen',2);
-- 商品分类cate id catename catedesc
create table cate(
id tinyint unsigned auto_increment key,
catename varchar(50) not null unique,
catedesc varchar(100) not null default ''
);
insert cate(catename) values('母婴');
insert cate(catename) values('服装');
insert cate(catename) values('电子');

-- 商品表products id productname, price,cateid
create table products(
id int unsigned auto_increment key,
productname varchar(50) not null unique,
price float(8,2) not null default 0,
cateid tinyint unsigned not null,
adminid tinyint unsigned not null
);
insert products(productname,price,cateid,adminid)
values('iphone9',9888,3,1),
('adidas',388,2,2),
('nike',888,2,2),
('奶瓶',288,1,1);

-- 查询products id productname price --- cate catename
select p.id,p.productname,p.price,c.catename
from products as p
join cate as c
on p.cateid=c.id;

-- 查询管理员 id username email -- provinces proname

select a.id,a.username,a.email,p.proname
from admin as a
join provinces as p
on a.proid=p.id;
-- 查询 products id productname price
-- cate catename
-- admin username email

select p.id,p.productname,p.price,c.catename,a.username,a.email
from products as p
join admin as a
on p.adminid=a.id
join cate as c
on p.cateid=c.id
where p.price<1000
order by p.price desc
limit 0,2;


-- products id productname price
-- cate catename
-- admin username email
-- provinces proname

测试外键

-- 测试外键
-- 新闻分类表 news_cate
create table news_cate(
id tinyint unsigned auto_increment key,
catename varchar(50) not null unique,
catedesc varchar(100) not null default ''
);

-- 新闻表 news
create table news(
id int unsigned auto_increment key,
title varchar(100) not null unique,
content varchar(1000) not null,
cateid tinyint unsigned not null
);

insert news_cate(catename) values('国内新闻'),
('国际新闻'),
('娱乐新闻'),
('体育新闻');

insert news(title,content,cateid) values('a1','aaaa1',1),
('a2','aaaa2',1),
('a3','aaaa3',4),
('a4','aaaa4',2),
('a5','aaaa5',3);

-- 查询news id title content
-- news_cate catename
select n.id,n.title,n.content,c.catename
from news as n
join news_cate as c
on n.cateid=c.id;

insert news(title,content,cateid) values('a6','aaaa6',45);

-- 添加外键

-- 新闻分类表 news_cate
create table news_cate(
id tinyint unsigned auto_increment key,
catename varchar(50) not null unique,
catedesc varchar(100) not null default ''
)engine=innodb;

-- 新闻表 news
create table news(
id int unsigned auto_increment key,
title varchar(100) not null unique,
content varchar(1000) not null,
cateid tinyint unsigned not null,
foreign key(cateid) references news_cate(id)
)engine=innodb;

insert news_cate(catename) values('国内新闻'),
('国际新闻'),
('娱乐新闻'),
('体育新闻');

insert news(title,content,cateid) values('a1','aaaa1',1),
('a2','aaaa2',1),
('a3','aaaa3',4),
('a4','aaaa4',2),
('a5','aaaa5',3);

-- 测试非法记录
insert news(title,content,cateid) values('b1','bbbb1',8);

-- 测试删除父表中的记录 和删除父表
delete from news_cate where id=1;

update news_cate set id=10 where id=1;

insert news_cate(catename) values('教育新闻');

-- 将教育新闻 改成教育
update news_cate set catename='教育' where id=5;
update news_cate set id=50 where catename='教育';

-- 添加外键名称

-- 新闻分类表 news_cate
create table news_cate(
id tinyint unsigned auto_increment key,
catename varchar(50) not null unique,
catedesc varchar(100) not null default ''
)engine=innodb;

-- 新闻表 news
create table news(
id int unsigned auto_increment key,
title varchar(100) not null unique,
content varchar(1000) not null,
cateid tinyint unsigned not null,
constraint cateid_fk_newscate foreign key(cateid) references news_cate(id)
)engine=innodb;

-- 删除外键
alter table news
drop foreign key cateid_fk_newscate;

-- 添加外键
alter table news
add foreign key(cateid) references news_cate(id);

-- 删除外键
alter table news
drop foreign key news_ibfk_1;

alter table news
add constraint cateid_fk_newscate foreign key(cateid) references news_cate(id);

insert news_cate(catename) values('国内新闻'),
('国际新闻'),
('娱乐新闻'),
('体育新闻');

insert news(title,content,cateid) values('a1','aaaa1',1),
('a2','aaaa2',1),
('a3','aaaa3',4),
('a4','aaaa4',2),
('a5','aaaa5',8);

alter table news
add foreign key(cateid) references news_cate(id);

-- 指定级联操作 delete cascade update cascade
alter table news
add foreign key(cateid) references news_cate(id)
on delete cascade on update cascade;

测试子查询

-- 测试子查询
-- 测试由in引发的子查询

select * from emp
where depid in (select id from dep);

select * from emp
where depid not in (select id from dep);

-- 学员stu
create table stu(
id tinyint unsigned auto_increment key,
username varchar(20) not null unique,
score tinyint unsigned not null
);
insert stu(username,score) values('king',95),
('queen',75),
('zhangsan',69),
('lisi',78),
('wangwu',87),
('zhaoliu',88),
('tianqi',98),
('ceshi',99),
('tiancai',50);


-- 分数级别level
create table level(
id tinyint unsigned auto_increment key,
score tinyint unsigned comment '分数'
);
insert level(score) values(90),(80),(70);

-- 查询出成绩优秀的学员

select score from level where id=1;

select id,username,score from stu
where score>=(select score from level where id=1);

-- 查询出没有得到评级的学员

select id,username,score from stu
where score<=(select score from level where id=3);

-- 由exists 引发的子查询

select * from emp where exists (select depname from dep where id=10);
select * from emp where exists (select depname from dep where id=1);


-- 带有any some all关键字的子查询
select * from stu
where score>= any(select score from level);

select * from stu
where score>= some(select score from level);

select * from stu
where score>= all(select score from level);

select * from stu
where score< all(select score from level);

select * from stu
where score=any(select score from level);

select * from stu
where score!=all(select score from level);

-- 创建一个user1表,id username
create table user1(
    id int unsigned auto_increment key,
    username varchar(20)
)select id,username from emp;

-- 将user表中的用户名写入到user1表中
insert user1(username) select username from user;

-- 将stu表中的tiancai用户名添加到user2表中
insert user2 set username=(select username from stu where id=9);

-- 去掉字段的重复值
select distinct(username) from user2;

-- 将user1和user2数据合并到一起
select * from user1
union
select * from user2;

测试自身连接

-- 测试自身连接
create table cate(
    id smallint unsigned auto_increment key,
    catename varchar(100) not null unique,
    pid smallint unsigned not null default 0
);
insert cate(catename,pid) values('服装',0);
insert cate(catename,pid) values('数码',0);
insert cate(catename,pid) values('箱包',0);

insert cate(catename,pid) values('男装',1);
insert cate(catename,pid) values('女装',1);
insert cate(catename,pid) values('内衣',1);

insert cate(catename,pid) values('电视',2);
insert cate(catename,pid) values('冰箱',2);
insert cate(catename,pid) values('洗衣机',2);

insert cate(catename,pid) values('爱马仕',3);
insert cate(catename,pid) values('lv',3);
insert cate(catename,pid) values('gucci',3);

insert cate(catename,pid) values('夹克',4);
insert cate(catename,pid) values('衬衫',4);
insert cate(catename,pid) values('裤子',4);

insert cate(catename,pid) values('液晶电视',10);
insert cate(catename,pid) values('等离子电视',10);
insert cate(catename,pid) values('背投电视',10);

-- 查询所有的分类信息,并且得到其父分类
select s.id,s.catename as scatename,p.catename  as pcatename
from cate as s
left join cate as p
on s.pid=p.id;

-- 查询所有的分类及其子分类
select p.id,p.catename  as pcatename,s.catename as scatename
from cate as s
right join cate as p
on s.pid=p.id;

-- 查询所有的分类并且得到子分类的数目
select p.id,p.catename  as pcatename,count(s.catename) as count
from cate as s
right join cate as p
on s.pid=p.id
group by p.catename
order by id asc;


scate 表
id | catename        | pid |
+----+-----------------+-----+
|  1 | 服装            |   0 |
|  2 | 数码            |   0 |
|  3 | 玩具            |   0 |
|  4 | 男装            |   1 |
|  5 | 女装            |   1 |
|  6 | 内衣            |   1 |
| 10 | 电视            |   2 |
| 11 | 冰箱            |   2 |
| 12 | 洗衣机          |   2 |
| 13 | 爱马仕          |   3 |
| 14 | lv              |   3 |
| 15 | gucci           |   3 |
| 16 | 夹克            |   4 |
| 17 | 衬衫            |   4 |
| 18 | 裤子            |   4 |
| 19 | 液晶电视        |  10 |
| 20 | 等离子电视      |  10 |
| 21 | 背投电视        |  10

pcate
id | catename        | pid |
+----+-----------------+-----+
|  1 | 服装            |   0 |
|  2 | 数码            |   0 |
|  3 | 玩具            |   0 |
|  4 | 男装            |   1 |
|  5 | 女装            |   1 |
|  6 | 内衣            |   1 |
| 10 | 电视            |   2 |
| 11 | 冰箱            |   2 |
| 12 | 洗衣机          |   2 |
| 13 | 爱马仕          |   3 |
| 14 | lv              |   3 |
| 15 | gucci           |   3 |
| 16 | 夹克            |   4 |
| 17 | 衬衫            |   4 |
| 18 | 裤子            |   4 |
| 19 | 液晶电视        |  10 |
| 20 | 等离子电视      |  10 |
| 21 | 背投电视        |  10

测试字符串函数

-- 测试字符串函数
-- char_length():得到字符串的字符数
select char_length('abc');

-- length():返回字符串的长度
select length('abc');

-- concat(s1,s2,....):将字符串合并成一个字符串

select concat('a','b','c');
-- 如果字符串中包含null,返回拼接结果就是null
select concat('a','b','c',null);

-- concat_ws(x,s1,s2,s2....):以指定分隔符拼接字符串
select concat_ws('-','a','b','c');
-- 如果null在拼接的内容中,则转化成空字符串
select concat_ws('-','a','b','c',null);
-- 如果分隔符为null,拼接的结果为null
select concat_ws(null,'a','b','c');
-- 将字符串转换成大写或者小写 upper()| ucase() lower()|lcase()
select upper('hello king'),ucase('hello imooc'),lower('hello admin'),lcase('hello everybody');

-- 字符串的反转reverse()
select reverse('abc');

-- left()|right():返回字符串的前几个字符或者后几个字符
select left('hello',2),right('hello',2);

-- lpad()|rpad():用字符串填充到指定长度
select lpad('abc',10,'?');
select rpad('abc',10,'!');

-- 去掉字符串两端的空格trim()|ltrim()|rtrim():

select concat('*',trim(' abc '),'*'),concat('*',ltrim(' abc '),'*'),concat('*',rtrim(' abc '),'*');

-- repeat():重复指定的次数
select repeat('hello',3);

-- replace():字符串

select replace('hello king','king','queen');

-- 截取字符串substring
select substring('abcdef',1,3);

-- 比较字符串

select strcmp('a','b');

测试日期时间函数

-- 测试日期时间函数
-- 返回当前日期
select curdate(),current_date();
-- 返回当前时间
select curtime(),current_time();
-- 返回当前的日期时间
select now(),current_timestamp(),sysdate();
-- 返回日期中的月份和月份的名称
select month('2017-02-19');
select month(curdate()),monthname(curdate());
-- 返回星期几
select dayname(now());
-- 返回一周内的第几天,0代表星期一
select dayofweek(now());
select week(now());
select year(now()),month(now()),day(now()),hour(now()),minute(now()),second(now());

-- datediff()计算两个日期相差的天数
select datediff('2019-03-06','2019-03-02');

其他函数测试

-- 测试其它常用函数
select version(),connection_id();

select user(),current_user(),system_user(),session_user();

-- 得到上一步插入操作产生auto_increment的值
select last_insert_id();

select md5('king');
-- password():密码加密算法
select password('root');

 




                    

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
Copyright © 2017-2020  萬仟网 保留所有权利. 粤ICP备17035492号-1
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com