1.常见命令:
数据库 database:
查看所有数据库:show databases;
创建数据库:create database 数据库;
进入数据库:use 数据库名;
表 table:
查看所有表:show tables;
查看某个库的所有表:show tables from 库名;
创建表:create table 表名(字段名 数据类型,... , ...);例:create table class(id int(10),name varchar(20),age int(10))
删除表:drop table 表名;
查看表结构:desc 表名
查看表中所有内容:select * from 表名;
在表中插入数据(添加行数据):insert into 表名(字段名,字段名,...)values (值,值,...);例:insert into class(id,name,age) values (1,'yuzu',27);
删除数据(删除某行):delete from 表名 where 字段名=...;
修改数据(就是更改某行的某个值) :update 表名 set 字段名=... where 字段名=...;
添加列:alter table 表名 add column (列名(即字段名),数据类型);
删除列:alter table 表名 drop column 列名(即字段名);
2. 条件查询 :
select 字段名/表达式/函数 from 表名 where 筛选条件
筛选条件中的一些关键字:
and or, not
and:where id=1 and 1=1
or:where id=1 or 1!=1
like: where name like %a% or name like _a_ ( %表示任意个字 符,_表示一 个,查询名字包含某些字母的字段)
between and:where id between 1 and 10 (查询id在1与10之间的字段)
in:where id in(1,2,4,6)(查询id在某些范围内的字段)
null :where id is null or name is not null(只能用is 或者 is not 来判断 )
concat : select concat(id,' and ','name'),age from 表名 (按行拼接查询字段,并输出)
group_concat:按组把多行数据显示在一行输出
select group_concat(id) from 表名(将id这一列放一行输出)
select group_concat(id,name) from 表名(拼接id,name,并将查询所有内容用一行输出)
select group_concat(name) from yuzu group by id(将id相同的name放一行输出)
ifnull( , 0):判断是否为null,是返回指定值,否则返回字段
isnull(字段): 判断是否为null,是返回1,否则返回0
3.排序查询
select 查询列表 from表名 order by 字段/表达式/函数/别名 DESC/ASC(高到低/低到高)
条件和排序可以同时
select 字段名,字段名,... from 表名 order by 1/2/...(就是根据查寻的第1/2/...列的升序结果进行排列显示,数字超过了要查询的列数就会报错)
这样就可以判断字段个数,也就是列的个数
select * from 表名 order by 1/2/3/...(1,2,3依次试,报错了就能知道有几列)
4.联合查询union
就是把有多个查询条件的语句,用union分割成多个查询语句(并集并去重)
联合查询可以查询不同表的内容,多个表无直接关系,但查询信息一样(列数一致)
union all 是不去重的