MySQL - 连接查询,联合查询,子查询

连接查询,联合查询,子查询


1. 连接查询
推荐使用内连接
内连接查询
select s.name,m.stu_id from student as s,mark as m where m.stu_id=s.id;
查询 student表里的name和mark表里的mark字段,从 student和mark表里,并简写表名,满足条件 student表的id要和mark表的stu_id对应。
也可以这样写
select s.name,m.stu_id from student as s inner join mark as m where m.stu_id=s.id;
表与表之间用inner join 连接

左连接查询(外连接查询)
select s.name,m.stu_id from student as s left join mark as m on m.stu_id=s.id;
以左边的表为基准,先把左边的表列出来,然后右边的表满足条件的对应到左边的表上,不满足条件的显示null

 

右连接查询(外连接查询)
select s.id,s.name,m.stu_id from student as s right join mark as m on m.stu_id=s.id;
同上,不同的是以右边的表为基准,


2. 联合查询
union all
select name,age from student union all select mark,stu_id from mark;
把两个查询语句用 union all 连起来,
注意⚠️:返回结果会以第一个查询语句的字段名来命名

 

3. 子查询
在括号里再进行一个查询
select id from student where id in (select stu_id from mark);
先执行小括号里的,把mark表里的stu_id查出来,
然后在student表里查满足条件的语句,然后返回。

类似
select id from student where id in (1,2,3,4);

----------------------------------------------------- 

猜你喜欢

转载自www.cnblogs.com/chefweb/p/9077927.html