MySQL数据库中,主要分为
DDL(数据库和表的操作语句)、
DML(表内数据的增删改操作语句)、
DQL(查询语句)等
DDL:
show databases; 显示所有数据库
use 数据库名; 使用该数据库
show create database 数据库名; 显示创建该数据库的SQL语句
create database 数据库名; 创建数据库
create database 数据库名 character set utf8; 创建指定字符编码的数据库
drop databse 数据库名; 删除数据库
create table 表名(id int ,name char(10),age int ); 创建表
show tables; 显示所有表
show create table 表名; 显示创建该表的SQL语句
alter table 表名 add id int ; 表中新增列
alter table 表名 modify id double; 修改表中列的属性
alter table 表名 change id id2 int; 修改表中列的名字和属性
alter table 表名 drop id; 删除表中的列
rename table 表名 to 新表名; 修改表格的名字
alter table 表名 character set utf8; 修改表的字符编码格式
DML:
insert into 表名 (字段1,字段2,字段3) values (值1,值2,值3) 新增值到表中
update 表名 set name = 'xx' where id =3; 更新表中数据
delete from 表名 where id = 2; 删除表中的数据
DQL:
select * from 表名 where id =3; 查询表中数据
select * from 表名 order by id desc | asc; 排序查询
select * from 表名 group by 字段; 分组查询
select * from 表名 where name like '%aa%'; 模糊查询
select * from 表名 limit (2,5); 分页查询
select * from 表名 where age between 20 and 30; 范围查询
select * from 表名 where id in (1,3,5); 部分查询
聚合函数:
select count(age) from 表名; 查询个数
select avg(age) from 表名 ; 查询平均值
select max(age) from 表名; 查询最大值
select sum(age) from 表名; 查询总和
select min(age) from 表名; 查询最小值
select ifnull(age,10) from 表名; 给null值一个默认值并查询
约束:
primary key 主键
auto_increment 自动增长
not null 不为空
unique 唯一
default 默认值
foreign key 外键
on update | delete cascade 外键级联
多表查询:
contact表:(从表)
user表:(主表)
contact表的user_id是user表外键
笛卡尔积现象:
在多表查询的时候,没有给定两表外键对应主键的条件,导致输出结果是主表匹配所有从表结果
有n张表一起查询,就等于要消除n-1次笛卡尔积现象
例:上面两张表消除的条件就是 contact.user_id = user.id
select * from contact , user where contact.user_id = user.id; 隐式内连接
select * from contact c inner join user u on c.user_id = u.id; 显式内连接
select * from contact c left outer join user u on c.user_id = u.id; 左外连接,保证左表的完整性
select * from contact c right outer join user u on c.user_id = u.id; 右外连接,保证右表的完整性
子查询:(子查询分为3种情况)
1.嵌套查询的结果仅有一个值时,常放在where 语句后作一个值使用
select * from contact where id = (select max(id) from )
2.嵌套查询的结果是一列数据时,常放在where语句后用in连接
select * from contact c , user u
where c.user_id in (select id from user where password like '%a%') and c.user_id = u.id ;
3.嵌套查询的的结果是多行多列数据时,常放在from语句后作一张表连接
select * from (select name , user_id from contact ) a, user u where a.user_id = u.id;