SQL基本操作
-
查看数据库
show databases;
-
使用某个数据库
use database_name; -- 这样才能够使用该数据库下的表
-
查看数据库下对应的表
show tables;
-
创建表
create table table_name(col_1 <data-type> <constrains>, col_2 <data-type> <constrains>,... ) -- egs:创建一个名为book的表,其中包含字符大小小于20且不为空的title,字符大小小于30不为空的author,并且设置title为主键 -- create table book(title varchar(20) not null, author varchar(30) not null, primary key(title))
-
查看表的信息
desc table_name; -- 或者 describe table_name;
-
查看表中的内容
select * from table_name; -- 查看表中的所有内容 select col_1,col_2,... from table; -- 查看表中感兴趣的内容 select * from table_name where ...; -- 查看满足条件的信息 -- where条件可以使用 -- 算术比较符 <, <=, >=, <, <>, = -- 逻辑运算符 and, or, not -- 集合运算符 union, intersect, except -- 成员符 in, not in -- 谓词 exists, all, any, unique -- 集合函数 count, sum, avg, max, min
-
向表中插入数据
insert into table_name values(data1,data2,...); -- 向表中所有数据都插入值 insert into table_name(col_1,col_2,...) values(data1,data2,...); -- 向表中感兴趣的数据插入值,但是其他未插入数据的都必须可以为NULL
-
更新表中的信息
update table_name set col_1="data1", col_2="data2" where ...; -- 向表中符合条件的修改数据,如果没有where作为限制,全部的值都会进行更新
-
修改表的结构
alter table table_name add col_name <constrains>; -- 添加一列 alter table table_name modify col_name <constrains>; -- 修改列对应的信息 alter table table_name drop col_name <constrains>; -- 删除某列
-
建立索引
create [unique] [cluster] index index_name on table_name(col_1 [sequence], col_2 [sequence],....) -- 使用unique的时候必须要保证col为主键 -- sequence 可以为ASC(升序), DESC(降序)
-
删除索引
drop index index_name on table_name; -- 删除表table_name上的索引
-
删除数据
delete from table where ...; -- 删除满足一定条件的数据
-
创建视图
create view view_name as subquery; -- subquery可以是很复杂的查询方式 -- eg: -- create view book_index as select * from book;
-
删除视图
delete view view_name; -- eg: -- drop view book_index;
-
函数查询
-- count 函数 -> 来用统计一个表中有多少条记录 -- sum函数 -> 用来计算字段值的和 -- avg函数 -> 同来求某个字段所有值的平均值 -- max函数 -> 用来求某一列中值的最大值 -- min函数 -> 用来求某一列中值的最小值