35

MySql数据库之子查询和高级应用

 4 years ago
source link: http://www.cnblogs.com/chao666/p/12045870.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

MySql数据库中的子查询:

子查询:在一条select查询语句中嵌套另一条select语句,其主要作用是充当查询条件或确定数据源。

代码案例如下:

例1. 查询大于平均年龄的学生:

select * from students where age > (select avg(age) from students);

例2. 查询学生在班的所有班级名字:

select name from classes where id in (select cls_id from students where cls_id is not null);

例3. 查找年龄最大,身高最高的学生:

select * from students where (age, height) =  (select max(age), max(height) from students);

MySql的高级应用:

1.将查询出来的数据添加到一个新的表中:

使用子查询将查询后的结果作为数据插入到新的表中,通过关键字 create table ... select ...实现,代码实现:

create table 表名(字段名1, 类型 约束,...) select 字段名 from 表名 where 查询条件

其执行流程是,先执行select语句通过where条件确定数据源,然后再将查询出来的数据插入到新创建的表中。

注意:在使用此方法时,要想给表中的指定字段添加数据,那么需要将查找出来的字段起一个和表中字段名相同的别名。

2.将查询的结果添加到表中:

使用子查询将查询后的结果作为数据插入到表中,通过关键字 insert into ... select ...实现,代码实现:

insert into 表名(字段名1,...) select 字段名1,.. from 表名 where 查询条件

其执行流程是,先执行select语句,将指定的数据通过where 条件筛选出来,然后再执行insert into 语句给指定的字段名进行数据的添加。

3.使用连接更新表中的某个字段的数据:

使用连接更新表中的字段数据,通过关键字update ... join..关键字实现,代码实现:

update 表1 join 表2 on 表1.字段 = 表2.字段 set 表1.字段 = 表2.字段

其执行流程是将两个表连接后,把表2中的字段的值设置给表1中的指定字段。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK