您的位置:首页 > 数据库 > MySQL

SQL复习笔记二(mysql)

2016-06-26 20:56 330 查看
约束

约束是添加在列上的,用来约束列

主键约束

特性:非空,唯一,被引用

创建表指定主键约束的两种形式

create table stu{
sid char(6) primary key,
........
}

或者
create table stu{
sid char(6) ,
........
primary key(sid)
}


修改表时指定主键及删除主键

alter table stu add primary key(sid);
alter table stu drop primary key;


主键自增长

create table stu{
sid char(6) primary key auto_increment,
........
}


非空约束

不能使用null的列可以添加 not null 关键字

create table stu{
sid char(6) primary key auto_increment,
stu_name varchar(20) not null,
........
}


唯一约束

不重复 unique 关键字

create table stu{
sid char(6) primary key auto_increment,
stu_name varchar(20) not null unique,
........
}


外键约束

一个表中的 FOREIGN KEY 指向另一个表中的 PRIMARY KEY。

FOREIGN KEY (tid) REFERENCES stu(sid)


合并结果集

合并的两张表要求列数和类型相同

union 去重复

union all 不去重复

连接查询

1.分类

内连接

外连接

左外连接

右外连接

全外连接

自然连接

2.内连接

*mysql 特有 select * from 表一 别名1 ,表二 别名2  where 别名1.xx = 别名2.xx
*标准 select * from 表一 别名1 inner join on 表二 别名2 on 别名1.xx = 别名2.xx
*自然 select * from 表一 别名1 natural join  表二 别名2


3.外连接

左外连接 select * from 表一 别名1 left outer join on 表二 别名2 on 别名1.xx = 别名2.xx 左表与右表不匹配的数据也会显示出来

右外连接 select * from 表一 别名1 right outer join on 表二 别名2 on 别名1.xx = 别名2.xx 右表与左表不匹配的数据也会显示出来

mysql 不支持全连接 但是可以通过union 来完成

通过以下方式

左外连接

union

右外连接

子查询 :

查询中嵌套查询

出现位置 where后作为条件存在

from后作为 表存在
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: