首页数据库MySQL中怎样进行内连接多表查询?

MySQL中怎样进行内连接多表查询?

时间2024-03-24 12:06:03发布访客分类数据库浏览1016
导读:这篇文章我们来了解MySQL中怎样进行内连接多表查询,在mysql中,可以使用join 或 inner join语句进行内连接查询,那么多表内连接查询的SQL语句是什么呢?接下来我们一起来学习一下。 本教程操作环境:windows7系统、m...

这篇文章我们来了解MySQL中怎样进行内连接多表查询,在mysql中,可以使用join 或 inner join语句进行内连接查询,那么多表内连接查询的SQL语句是什么呢?接下来我们一起来学习一下。

本教程操作环境:windows7系统、mysql8版本、Dell G3电脑。

内连接

join 或 inner join

SQL语句:select * from student inner join score on student.Num=score.Stu_id;

此时的语句就相当于:select * from student,score where student.ID=course.ID;

扩展资料:

外连接

1.左连接 left join 或 left outer join

SQL语句:select * from student left join score on student.Num=score.Stu_id;

2.右连接 right join 或 right outer join

SQL语句:select * from student right join score on student.Num=score.Stu_id;

3.完全外连接 full join 或 full outer join

SQL语句:select * from student full join score on student.Num=score.Stu_id;

通过上面这三种方法就可以把不同的表连接到一起,变成一张大表,之后的查询操作就简单一些了。

而对于select * from student,score; 则尽量不使用此语句,产生的结果过于繁琐。

交叉连接

cross join,没有where指定查询条件的子句的交叉联接将产生两表的笛卡尔积。

SQL语句:select * from student cross join score;

结构不同的表连接

当两表为多对多关系的时候,我们需要建立一个中间表student_score,中间表至少要有两表的主键。

SQL语句:select s.Name,C.Cname from student_score as sc left join student as s on s.Sno=sc.Sno left join score as c on c.Cno=sc.Cno

select C_name,grade from student left join score on student.Num=score.Stu_id where name='李五一';
    

红色部分即中间表,是集合两表所有内容的一张总表。

UNION操作符用于合并两个或多个select语句的结果集。

UNION内部的SELECT语句必须拥有相同数量的列,每个列也必须拥有相似的数据类型,每条SELECT语句中的列的顺序必须相同。

select Num from student union select Stu_id from score;
    

union操作符是默认查重的,如果允许重复的值,就可以使用union all 。对于两张结构相同的表,union也可以把他们合并成一张表:

select * from student1 union select *from student2;
    

子查询

有时候,查询时需要的条件是另外一个select语句的结果,就会使用到子查询。

1.带IN关键字的子查询

SQL语句:select * from student where Num IN(select Stu_id from score);

2.带EXISTS关键字的子查询

exists内查询返回一个真价值,若返回true时,外查询进行查询,否则外查询不进行查询。

SQL语句:select * from student where exists(select * from score where C_name='计算机');

3.带ANY关键字的子查询

使用ANY关键字只要有一个满足,就通过该条件来执行外查询。

SQL语句:select sname,(date_format(from_days(now())-to_days(birthday)),'%Y')+0) as '年龄' from student where birthday> ANY(select birthday from student where bumen='计算机系');

4.带ALL关键字的子查询

使用ALL关键字必须满足所有的内层查询语句返回的所有结果,才执行外查询

SQL语句:select sname,(date_format(from_days(now())-to_days(birthday)),'%Y')+0) as '年龄' from student where birthday> ALL(select birthday from student where bumen='计算机系');

以上就是关于MySQL中进行内连接多表查询的介绍,上述SQL语句具有一定的借鉴价值,有需要的朋友可以参考学习,希望对大家学习MySQL内连接多表查询有帮助,想要了解更多可以继续浏览网络其他相关的文章。

文本转载自脚本之家

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: MySQL中怎样进行内连接多表查询?
本文地址: https://pptw.com/jishu/652048.html
c语言判断函数方法有哪些,怎样应用判断学生成绩 c语言函数调用的方式有多少种

游客 回复需填写必要信息