MySQL5.7数据库介绍表连接、子查询、外键


当前第2页 返回上一页

1

select * from 表1 right join 表2 on 表1.列 = 表2.列;

子查询

某些情况下,当进行查询的时候,需要的条件是另外一个select语句的结果,这个时候,就要使用到子查询

1

select * from 表 where 表(子查询语句)-- 查询出students中身高最高的男生。显示名字和身高select s.name, s.high from students s where high=(select max(high) from students) and gender="男";-- 查询出高于平均身高的学生信息select * from students where high>(select avg(high) from students);-- 查询学生班级号cls_id能够对应的学生信息select * from students where cls_id in (select id from students);-- 查询最大年龄的女生的idselect * from students where id=(select max(id) from students where gender="女") and  gender="女";

在这里插入图片描述

自关联

简单理解为自己与自己进行连接查询

1

-- 查询广东省下的所有广东市select * from cities c inner join provinces p on c.provinceid=p.provinceid having p.province="广东省";-- 查询广东省下的所有广东市-- 自关联select * from areas a inner join areas b on a.id=b.pid having a.name="广东";

在这里插入图片描述
在这里插入图片描述

外键

外键介绍

  • MySQL的外键(foreing key)是表的一个特殊字段。对于两个具有关联关系的表而言,相关联字段的主键所在表就是主表(父表),外键所在的表是从表(子表)。
  • 注意: 主键不能包含空值,但允许在外键中出现空值,也就是说,只要外键的每个非空值出现在指定的主键中,这个外键的内容就是正确的。

创建表时设置外键约束

  • 当创建外键的时候,必须先删除从表才能删除主表。
  • 主表需存在时创建从表。
  • 从表的外键关联必须是主表的主键,并且主键与外键的类型必须保持一致。

1

[constraint 外键名] foreign key (字段名 [,字段名2, ...]) references <主表名> 主键列1 [, 主键列2, ...]

1

2

3

4

5

6

7

8

9

10

-- 创建班级表create table classes(

    id int(4) not null primary key,

    name varchar(36));-- 创建学生表create table student(

    sid int(4) not null primary key,

    sname varchar(30),

    cid int(4) not null);-- 创建直接含有外键关系的学生表create table student(

    sid int(4) not null primary key,

    sname varchar(30),

    cid int(4) not null,

    constraint pk_id foreign key (cid) references classes(id));-- 通过alter来添加外键关系alter table student add constraint pk_id foreign key (cid) references classes(id);-- 删除外键约束alter table student drop foreign key pk_id;

在这里插入图片描述

在这里插入图片描述

相关免费学习推荐:mysql数据库(视频)

以上就是MySQL5.7数据库介绍表连接、子查询、外键的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

navicat怎么查看表中的外键

navicat设置外键保存不了怎么办

mysql5.7数据库介绍表连接、子查询、外键

手把手教你在mysql5.7中搭建主从复制

mysql5.7如何实现双主同步部分表的过程介绍

navicat外键怎么设置

在mysql中如何进行子查询?

centos7安装和配置mysql5.7的方法分享

navicat设置外键报错1025怎么办

mysql5.7在windows7下数据位置修改方法详解

更多相关阅读请进入《mysql5.7》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...