接下来的一些内容,我们需要提前学一些简单的sql语句,方便大家理解接下来的知识。
DDL—数据定义语言(Create,Alter,Drop,DECLARE)
DML—数据操纵语言(Select,Delete,Update,Insert)
DCL—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK)
DQL---数据查询语言(select)
DML(data manipulation language):
它们是SELECT、UPDATE、INSERT、DELETE,就象它的名字一样,这4条命令是用来对数据库里的数据进行操作的语言
DDL(data definition language):
DDL比DML要多,主要的命令有CREATE、ALTER、DROP等,DDL主要是用在定义或改变表(TABLE)的结构,数据类型,表之间的链接和约束等工作上,他们大多在建立表时使用
DCL(Data Control Language):
是数据库控制功能。是用来设置或更改数据库用户或角色权限的语句,包括(grant,deny,revoke等)语句。在默认状态下,只有sysadmin,dbcreator,db_owner或db_securityadmin等人员才有权力执行DCL
接下来我们逐步学习SQL语句,在学习之前我们先注意一下SQL语句的注意事项.
1.每条SQL语句结束时要以;做为结束符.(除了use命令)
2.SQL语句的关键字不区分大小写(除了库名字和表名字)
3.在查询数据库信息或者表信息时,可以以\G做为结束符,表示以文本模式输出
4.当你不需要一条语句输出的结果以\c结束,不可以使用ctrl+c,否则登出mysql.
5.我们可以在命令行执行sql语句,要通过mysql -e参数
mysql -e "show databases /G" 显示到shell上
6.如果需要获取SQL语句的帮助可以用help命令
如:help create
如果需要进一步获取帮助,可以继续使用help命令
如:help create database
1.DDL数据库定义语句
建立数据库以及查询
create database db;
create database db CHARACTER SET = 'utf8'
show databases;
show create database db;
alter database db CHARACTER SET = 'latin1';
修改库名只需要改数据库目录名称
drop database db;
建立表以及查询
use db
类型
create table t1(id int(6),name char(10));
create table t1(id int(6),name varchar(10));
日期时间类型
date类型
create table t4(aa date);
insert into t4 values('2010-04-01'),(20100401);
select * from t4;
+------------+
| aa |
+------------+
| 2010-04-01 |
| 2010-04-01 |
+------------+
time类型
create table t5(showttime time);
insert into t5 values ('11:11:11'),('11:11'),('111111');
select * from t5;
+-----------+
| showttime |
+-----------+
| 11:11:11 |
| 11:11:00 |
| 11:11:11 |
+-----------+
出现的问题
create table t6 (a_data data,a_time time);
insert into t6 values('1978-4-6',123412),(651212,'3:5:6');
select * from t6;
+------------+----------+
| a_date | a_time |
+------------+----------+
| 1978-04-06 | 12:34:12 |
| 2065-12-12 | 03:05:06 |
+------------+----------+
年份的范围00-69为2000-2069&&70-99为1970-1999
year类型
create table t7 (year year);
insert into t7 values(2003),(04),(53),(89),(90);
select * from t7;
+------+
| year |
+------+
| 2003 |
| 2004 |
| 2053 |
| 1989 |
| 1990 |
+------+
datetime和timestamp类型
timestamp 时间戳类型,输入null,显示当前时间。datetime则会显示null
datetime 如果name改变,时间不改变。例如:QQ的申请时间
timestamp 如果name改变,时间会改变成现在时间。例如:提示上次登录时间
values(now()) now()函数,当前时间函数,申请帐号时可以触发。
create table t8(f_datetime datetime,f_timestamp timestamp);
insert into t8 values('1999-11-11 11:11:11','2002-11-111:11:11');
insert into t8 values(19991111111111,20021111111111);
insert into t8 values(now(),null);
select * from t8;
+---------------------+---------------------+
| f_datetime | f_timestamp |
+---------------------+---------------------+
| 1999-11-11 11:11:11 | 2002-11-11 11:11:11 |
| 1999-11-11 11:11:11 | 2002-11-11 11:11:11 |
| 2012-03-21 21:05:21 | 2012-03-21 21:05:21 |
+---------------------+---------------------+
ENUM和SET类型
create table t10(sex ENUM('M','F'));
insert into t10 values('M'),('m'),('F'),('aa'),(null);
select * from t10;
+------+
| sex |
+------+
| M |
| M |
| F |
| |
| NULL |
+------+
create table t11 (type SET('a','b','c','d','e'));
insert into t11 values(a);
insert into t11 values('b,c');
insert into t11 values('J');
select * from t11;
+------+
| type |
+------+
| a |
| b,c |
| |
+------+
insert into t11 values('b,c,e,f');既有合法字符又有非法字符
select * from t11;
+-------+
| type |
+-------+
| a |
| b,c |
| |
| b,c,e |
+-------+
练习:
创建表test id name money sex hobby email qq shenfezheng jointime
create table test(id tinyint,name char(10),money float(10,2),sex enum('M','F'),hobby set('a','b','c'),email varchar(50),qq char(15),shenfenzheng char(18),jointime datetime);
mysql> rename table test to newtest;
mysql> alter table test change id uid smallint;
mysql> alter table test modify id smallint;
修饰符(约束)
无符号 unsigned
用0补齐 zerofill
desc t11;
+-------+--------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------------------+------+-----+---------+-------+
| type | set('a','b','c','d','e') | YES | | NULL | |
+-------+--------------------------+------+-----+---------+-------+
not null约束
create table t12 (id int,sex enum('M','W') NOT NULL );
desc t12;
+-------+---------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------------------+------+-----+---------+-------+
| id | int(10) unsigned zerofill | YES | | NULL | |
| sex | enum('M','W') | YES | | NULL | |
+-------+---------------------------+------+-----+---------+-------+
insert into t12(id) values(1);
Query OK, 1 row affected (0.00 sec)
select * from t12;
+---+-----+
|id | sex |
+---+-----+
| 1 | NULL|
+---+-----+
DEFAULT约束
create table t13 (id int ,sex enum('M','W') NOT NULL default 'M' );
desc t13;
+-------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| sex | enum('M','W') | YES | | M | |
+-------+---------------+------+-----+---------+-------+
insert into t13(id) values(3);
select * from t13;
+------+------+
| id | sex |
+------+------+
| 2 | M |
| 3 | M |
+------+------+
AUTO_INCREMENT修饰符自动增长只适用于int字段 一般用于主键 一个表只能有一个
create table t14(id int auto_increment primary key,name char(10) not ll);
desc t14
+-------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | char(10) | NO | | NULL | |
+-------+----------+------+-----+---------+----------------+
insert into t14(name) values(zhb);
insert into t14(name) values('haha');
select * from t14;
+----+------+
| id | name |
+----+------+
| 1 | zhb |
| 2 | haha |
+----+------+
索引添加删除
show index from t20\G
show create table t20;
drop index index_name on table_name;
create index index_name on table_name(列名);
alter table table_name add index(列名);
索引建立
create table t15(id int not null ,name char(10),index(id));
desc t15;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | MUL | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
向已有表添加索引
create table t16(id int not null ,name char(10));
desc t16;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
create index id on t16 (id);
alter table t17 add index(id);
desc t16;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | MUL | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
删除索引
drop index id on t16;
desc t16;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
查询索引
show index from t16;
UNIQUE索引(允许空值,null != null)
create unique index id on table_name(id);
create table t17(id int ,name char(10),unique(id));
desc t17;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | YES | UNI | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
insert into t17 values(null,'zhb');
select * from t17;
+------+------+
| id | name |
+------+------+
| NULL | zhb |
+------+------+
PRIMARY KEY(主键约束 值唯一 uniq和not null的结合 可作用多列 不可两列同时相同,单列重复可以)
alter table t22 drop primary key;
alter table t22 add primary key(id);
create table t18(id int,name char(10),primary key(id));
desc t18;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | PRI | 0 | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
insert into t18 values(1,'zhb');
select * from t18;
+----+------+
| id | name |
+----+------+
| 1 | zhb |
+----+------+
insert into t18 values(1,'zhb');
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY' 不允许重复
删除主键
mysql> alter table t19 drop primary key;
向已有表添加主键
mysql> alter table t19 add primary key(id);
在多个列上建立主键,不可多次添加主键
create table t19(id int,name char(10),primary key(id,name));
desc t19;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | PRI | 0 | |
| name | char(10) | NO | PRI | | |
+-------+----------+------+-----+---------+-------+
insert into t19 values(1,'zhb');
insert into t19 values(1,'zorro');
select * from t19;
+----+-------+
| id | name |
+----+-------+
| 1 | zhb |
| 1 | zorro |
+----+-------+
外键myisam引擎不支持只能用innodb引擎
create table dpmnt(id int not null,name char(10) not null,primary key(id)) type = INNODB;
desc dpmnt;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | char(10) | NO | | NULL | |
+-------+----------+------+-----+---------+-------+
建立外键
create table emp (id int not null, name char(10) not null,fk_dpmnt int not null ,primary key(id),index (fk_dpmnt),foreign key (fk_dpmnt) references dpmnt(id)) type=innodb;
desc emp;
+----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | char(10) | NO | | NULL | |
| fk_dpmnt | int(11) | NO | MUL | NULL | |
+----------+----------+------+-----+---------+-------+
insert into dpmnt values(1,hr);
insert into dpmnt values(2,'yw');
insert into emp values(10,'zhb',3);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (db
.emp
, CONSTRAINT emp_ibfk_1
FOREIGN KEY (fk_dpmnt
) REFERENCES dpmnt
(id
))
fk_dpmnt字段的数据必须得是dpmnt表里有的不然报错...
即使表存在外键约束,MySQL还允许我们删除表,并且不会产生错误。这是删除外键的方法。
alter table emp drop foreign key emp_ibfk_1;
删除外键
全文本索引
mysql> desc t22;
create table t22(id int,name char(10),fulltext(name));
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | char(10) | YES | MUL | NULL | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)
练习:
创建表test id name money sex hobby email qq shenfezheng jointime
create table test(id tinyint,name char(10),money float(10,2),sex enum('M','F'),hobby set('a','b','c'),email varchar(50),qq char(15),shenfenzheng char(18),jointime datetime);
1.添加约束
create table test1 ( id int primary key auto_increment, name char(20) not null, money float(10,2) not null, sex enum('M','F') not null default 'M', hobby set('a','b','c') not null default 'a', qq char(15) unique, email char(50), jointime datetime,index(email));
2.删除掉所有的约束
alter table test1 modify id int; 删除auto_increment
alter table test1 drop primary key; 删除primary key
alter table test1 modify id int; 删除 not null
alter table test1 modify name char(10);
alter table test1 modify money float(10,2);
alter table test1 modify sex enum('M','F');
alter table test1 modify hobby set('a','b','c');
drop index qq on test1;
drop index email on test1;
3.在添加约束
alter table test1 add primary key(id);
alter table test1 modify id int auto_increment;
show tables;
show create table t1;
ALTER table t2 RENAME t1;
alter table t2 MODIFY a tinyint not null,CHANGE b c char(20);
mysql> alter table test2 modify id tinyint,change name testname char(30); 重命名时名字不能是关键字,rename等
mysql> alter table tt2 change id did int;
create table members ( id int(11),name char(10),tel char(15));
alter table members ADD qq int;
alter table members drop qq;
alter table members add qq int after name ;
alter table members add phone first;
alter table test1 modify qq char(15) after id;
drop table t1;
2.DML 数据库操纵语句
insert
mysql> INSERT INTO members ( member_id,fname,lname,tel,email) VALUES ( NULL,'john','Doe','1234567','[email protected]');
mysql> INSERT INTO members VALUES ( NULL,'kyo','oyk','7654321','[email protected]');
mysql> INSERT INTO members (fname,lname,email,tel,member_id) VALUES ('bob','kk','[email protected]','22334455',NULL);
update
mysql> UPDATE members SET email = '[email protected]' WHERE member_id = 3;
mysql> UPDATE members SET email = '[email protected]',lname = 'ho' WHERE member_id = 2;
delete
mysql> DELETE FROM members;
mysql> DELETE FROM members WHERE member_id = 1;
sql语句使用
连接数据库
mysql -u root -p123 -h localhost
查看服务器状态
show staus;
显示所有库名
show databases;
使用数据库
use db;
显示当前数据库中的所有表
show tables;
查看表结构
desc tables;
select查询语句(默认乱序,可以指定多列显示顺序)
select name from tables; 从表中查询指定列
select id,name,sal from tables; 指定多个列名
select * from tables;查询所有的列
select distinct id from tables; 去掉重复行
select name from tables limit 5; 显示前5行
select name from tables limit 5,5;显示从第5行开始的后5行即5-10行
select name from db.t1;没有使用use进入db库时查询db库的t1表
select t1.name from db.t1; 指定库的表 指定表的列
显示mysql中第一个用户名字?
在shell命令行显示用户的名字和密码
显示mysql中的前3个用户
修改root帐号密码为456
[root@uplooking 桌面]# /usr/local/mysql/bin/mysqld_safe --user=mysql --skip-grant-tables &
mysql> update mysql.user set password=password('123456') where user='root' and host='localhost';
[root@uplooking 桌面]# killall mysqld
[root@uplooking 桌面]# service mysqld restart
[root@uplooking 桌面]# /usr/local/mysql/bin/mysql -uroot -p123456
排序检索语句
select id,name from t1 order by id; 按id排序
select id,name from t1 order by id,name;先按id排序id相同在按name排序
select id,name from t1 order by id desc; 按id反向排序
select id,name from t1 order by id desc,name; 先按id反向排序再按名字排序
select id,name,sal from t1 order by sal desc limit 1;查找工资最高的人
where子句
select id,name,sal from t1 where name='tom'; 查找tom的信息
where 子句的操作符
= 等于
<> 不等于
!= 不等于
< 小于
<= 小于等于
大于
= 大于等于
between 5 and 10 在两个值之间
is null 空值
is not null 非空值
select id,name from t1 where id>5 and name='tom'; and操作符表示两个条件都要满足 与操作
select id,name from t1 where id=10 or name='tom';or操作符表示满足任意条件 或操作
select id,name,sal from t1 where id=10 or id=20 and sal > 5000; id为10的 或者id为20并且薪水大于5000的;and优先执行
select id,name,sal from t1 where (id=10 or id=20) and sal > 5000;id为10或者20 并且薪水大于5000的
select id,name,sal from t1 where id in (10,20,30);id在 10 20 30 中的记录
这条语句用or可以做到相同的结果,那in的好处
1.in的语法更加直观
2.in的计算次序更容易管理(操作符少)
3.in 一般比or执行的更快
4.in的最大优点可以包含其他子句 or不行
取最高薪水的人
select * from test2 where money=(select money from test2 order by money desc limit 1);
select * from test where id=(select id from test order by id desc limit 1); id号最高的人
复制表结构
create table test1 as select * from test where 1>2; 只复制表结构,不复制数据
create table test2 as select * from test; 完全复制,包括数据
select id,name,sal from t1 where id not in (10,20,30); id不在10 20 30的记录 not找到不匹配的记录更简单
通配符%匹配多个字符_匹配一个字符
select id,name from t1 where name like 'jer%';模糊查询名字为jer开头的记录
select id,name from t1 where name like 'j%y'; 匹配j开头y结尾的
select id,name from t1 where name like '_err%' 匹配e前边有一个字符的记录
原则:
尽量少使用通配符,如果其他操作符能做到就不要使用通配符
在确实需要通配符时,尽量不要使用%erry 这种用法搜索起来会更慢
至于使用位置,使用错了得不到想要的结果
正则表达式的使用regexp
select id,name from t1 where name regexp 'je*';调用正则匹配je开头
select id,name from t1 where name regexp 'y$';
语句的拼接
select concat(id ,'(',name,')') from t1 将id和name 拼接为1列 oracle用||
select concat(id ,'(',name,')') all_name from t1 别名也可以使用as
select sal*12 from t1 计算全年薪水 + - * /
函数使用
select upper(name) as new_name from t1; 将名字转换为大写 lower 小写
group by 分组 必须在where之后 分组前过滤 having 可以分组后过滤
sum max min avg count year month day hour minute second
select count() from emp group by sex;
select count() as num emp group by id having num > 3;
where 条件必须在group by前面,having可以在group by 后面
1.建立员工档案表
要求字段:员工员工编号,员工姓名,性别,工资,email,入职时间,部门。
create table emp(uid int primary key auto_increment,name char(10) not null,sex enum('M','F') not null default 'M',money float(10,2),email varchar(50),jointime datetime,dname char(20),unique(email));
2.合理选择数据类型及字段修饰符,要求有NOT NULL,auto_increment, primary key等。
3.查看表的结构
desc emp;
4.新增qq和tel字段,要求tel字段位于email前,要求入职时间是最后一个字段
alter table emp add tel char(11) after money;
alter table emp add qq char(15);
alter table emp modify jointime datetime after qq;
5.把email字段修改成mailbox
alter table emp change email mailbox varchar(50)
6.向表里添加10条记录
7.修改其中两条记录的tel和mailbox
update emp set tel=18611112222 where name='lici';
update emp set mailbox='[email protected]' where name='lici';
8.查看所添加记录
9.查看姓名和入职时间记录
10.查询入职时间在2003年以前的
select name,jointime from emp where year(jointime)<2013;
11.查询工资最高和最低的员工姓名
select name,money from emp where money=(select min(money) from emp);
select name,money from emp where money=(select max(money) from emp);
12.查询平均工资
13.统计男员工人数、女员工人数
select count(*) from emp group by sex;
14.按照入职时间先后进行排序,并显示前5位员工姓名
select * from emp order by jointime limit 5;
笔记补充:
create table t3 (id int unsigned); unsigned取值范围无符号(0,255)
char(10) 长度 int(6) zerofill 不足6位前面用0自动补齐,例如:员工号
oracle的 OLAP数据库 写入少,读多 carchar利用率高 。 OLTP在线数据库,比较多的更改用char
ENUM和SET 枚举类型
enum单选,可以为空 例如性别 set 多选 喜爱
UNIQUE 不可以重复值,但是可以为空。null != null
create unique index ID on t1(ID);
primary key 可以用多格列,不允许两个列
外键:部门did约束,员工did范围不超过部门did
幻读:事物提交之前读取的数据
脏读:在内存中,未写到硬盘中而读取的数据
start transaction; 开启事物。开启后,insert数据 再create,会自动提交数据。不再同一终端可以create,不会提交。例如:申请账号,返回,上一步等选项