什么是表?
表:table
逻辑上 每一个表在数据库中包含了行和列
表可以为0行 但至少要有一列 表同样支持索引的查询
物理上 每个表由一个或多个文件在磁盘上保存
每一个表的存储 在数据库中目录中都有对应的文件系统格式
表空间:比表大而比数据库小的物理单位
创建表:
help create table
create [temporary] table [if not exists] tbl_name ( // 新建一个表
(create_definition,...)
[table_option]...
);
create [temporary] table [if not exists] tbl_name ( // 选择已知表的字段并创建
[(create_definition,...)]
[table_option] ...
select [select_statement]
create [temporary] table [if not exists] tbl_name ( // 参照已知表进行创建
{ like old_tbl_name | (like old_tbl_name)} 字段与字段间用 , 隔开
查看如何创建:
show create table tbl_name;
---------------------------------------------------------------------------
e.g.
create table employee (
id int not null,
last_name char(30) not null,
first_name char(30) not null,
unique (id),
index (last_name, first_name)
);
create table ... select can create a table that is empty or non-empty, depending on what is returned by the select part
create table ... like creates an empty table using the definition of another existing table
create table tbl_name (
id int unsigned auto_increment not null,
---------------------------------------------------------------------------
内置了n多的函数 增加使用效果
参照 mysql 官方手册
聚合函数
count(*), max(), min(), avg(), sum()
除了函数 还可以使用变量
set @num=10 // 设置变量为10
应用声明要使用@
===========================================================================
修改表结构:
alter table t1 change a b interger; // 把一个interger列的名称从a变到b
alter table t1 modify b b biginit nou null // 修改类型 修改定义和位置 而不改变字段名
可以使用first或after col_name在一个表行中的某个特定位置添加列。默认把列添加到最后。您也可以在change或modify语句中使用first和after
---------------------------------------------------------------------------
alter table tbl_name modify col_name col_definition 改变位置
alter table tbl_name change col_name col_definition
---------------------------------------------------------------------------
添加一个新字段
add {first | after} col_name col_definition
添加索引:
add {index|key} [index_name] [index_type] (col..)
index_type: btree、hash、rtree、fulltext
删除格式:
drop col_name; //删除字段
drop primary key; // 删除主键
drop {index|key} index_name; //
insert 还支持一次插入多行
修改数据 : dml
update table_name set col1=val1[, ...] [where clause] //需要指定条件 否则更新所有列
e.g. update knight set age=18 where uid=1
help truncate;
select last_insert_id(); //记录最后的id 行
truncate table table_name; // 清空表中的所有数据 并重1开始计数
---------------------------------------------------------------------------
多表查询:
两张表如何组织起来:
join, 连接 基于某种方式 把表组合起来
连接的种类:
1.交叉连接,cross join 笛卡尔乘积 // 一般很少用 但是适用所有情况 在内存中临时存储 在 磁盘上存储 结果 所以是非常非常的慢
2.内连,,inner join 对称连接
基于等值条件 左右表同时出现 且值相等
如果字段名字相同 就要引用表前缀 table_name.col_name
3.外连接 outer join
左外连接 left join on
左边有 右边显示null // 左表显示的有的全显示 右边有的显示 没有的显示null
右外连接 right join [on] on 指条件
左边null 右边显示
全外连接 full join
都显示出来 左表有的右表没有 右表有的左表没
4.自连接 self join 自己与自己相连接
5.union 结果组合连接起来
将两个表的查询结果合成一个
